The Java socket bottom layer uses TCP/IP protocol communication, the communication details are encapsulated, we just need to specify IP, port, we can easily create TCP or UDP connection, network communication. Data is read and written, and can be manipulated using the stream we are familiar with.
In TCP communication, the server is a one-to-many relationship with the client, such as
After the client initiates the connection request, the server side responds and creates a socket instance that communicates with the client side. After the communication is complete, the client side and the server side of the socket instance are closed and destroyed, this communication ends.
The three-time handshake and closing of the connection four times the wave process is not a table, follow-up article detailed introduction. Look at the specific code below
Service-side code
PackageCom.coshaho.learn.socket;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.ServerSocket;ImportJava.net.Socket;/*** Socketserver.java Create on December 16, 2017 11:42:03 * class function Description: Socket service side * @Author Coshaho*/ Public classSocketserver { Public Static voidMain (string[] args)throwsException {//Create a service-sideServerSocket Server =NewServerSocket (10000); //server-side blocking Listener Client connection request//When a connection request is received, a socket instance is created to communicate with the clientSocket client =server.accept (); //get InputStream Read DataInputStream in =Client.getinputstream (); byte[] B =New byte[1024]; //after the client closes the output stream, the server reads the-1 flag while(-1! =In.read (b)) {System.out.println (NewString (b)); } //get outputstream output dataOutputStream out =Client.getoutputstream (); Out.write ("Hello, client". GetBytes ()); //output end, output stream offClient.shutdownoutput (); System.out.println ("Server close." +System.currenttimemillis ()); Server.close (); }}
Client code
PackageCom.coshaho.learn.socket;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.Socket;/*** Socketclient.java Create on December 16, 2017 11:42:53 * class function Description: Socket client * @Author Coshaho*/ Public classsocketclient { Public Static voidMain (string[] args)throwsException {//Request connection Server, handshake succeeded, return socket instanceSocket client =NewSocket ("127.0.0.1", 10000); //get input and output stream, read and write data (same as server data read and write operation)InputStream in =Client.getinputstream (); OutputStream out=Client.getoutputstream (); Out.write ("Hello, Server". GetBytes ()); Client.shutdownoutput (); byte[] B =New byte[1024]; while(-1! =In.read (b)) {System.out.println (NewString (b)); } System.out.println ("Client close." +System.currenttimemillis ()); Client.close (); }}
Getting Started with Java sockets