1. Server-side code
PackageCom.lanber.socket;ImportJava.io.DataInputStream; ImportJava.io.DataOutputStream; Importjava.io.IOException; ImportJava.net.ServerSocket; ImportJava.net.Socket; Public classServerdemo {/*** Note: The socket is sent and received synchronously, that is, the client sends a message, the server must first receive this information, * and then can send information to the client, otherwise there will be a run-time error. * @paramargs*/ Public Static voidMain (string[] args) {ServerSocket ss=NULL; Try{SS=NewServerSocket (8888); //after the server receives the client's data, create a socket for the client dialogSocket socket =ss.accept (); //the output stream used to send data to the clientDataOutputStream dos =NewDataOutputStream (Socket.getoutputstream ()); //The input stream used to receive the data sent by the clientDataInputStream dis =NewDataInputStream (Socket.getinputstream ()); System.out.println ("The server received a connection request from the client:" +Dis.readutf ()); //the server sends the connection success confirmation message to the clientDos.writeutf ("Accept connection request, connection successful!")); //when you do not need to continue using this connection, close the connectionSocket.close (); Ss.close (); } Catch(IOException e) {e.printstacktrace (); }}}
2. Client code
PackageCom.lanber.socket;import Java.io.DataInputStream;ImportJava.io.dataoutputstream;import java.io.IOException;ImportJava.io.OutputStream;ImportJava.net.Socket;Importjava.net.UnknownHostException; Public classClientdemo {/***@paramargs*/ Public Static voidMain (string[] args) {socket socket=NULL; Try{Socket=NewSocket ("localhost", 8888); //gets the output stream for the client to send data to the server sideDataOutputStream dos =NewDataOutputStream (Socket.getoutputstream ()); //gets the input stream used to receive data sent from the server sideDataInputStream dis =NewDataInputStream (Socket.getinputstream ()); //client sends data to server sideDos.writeutf ("I'm the client, request a connection!")); //print out the data received from the server sideSystem.out.println (Dis.readutf ()); //when you do not need to continue using this connection, remember to close OhSocket.close (); } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } }
}
Java Socket Basics Example