Socket communication refers to the communication between two programs of two computers, each of which is called a socket, but is divided into clients and servers.
Java.net provides the serversocket and socket classes, respectively, for the server and client.
Communication process:
To establish a socket connection, the client program requests a connection, the server program listens on all the ports, determines if there is a client server request, when the client requests a port connection, the server binds the other's IP and port number to form a socket, so that the server and the client set up a private virtual connection, Can communicate with each other, after the end of the communication to remove the virtual connection.
Programming Steps: The server establishes a server socket ServerSocket, and specifies the port number to listen for client requests, and then establishes a socket to communicate with the client, and the client establishes a socket at the same port to communicate with the server.
Java.net contains the above two classes:
Main Method Description:
ServerSocket (int port) creates a server socket object on the specified port
ServerSocket (int port,int count) count is the maximum number of connections
Sorket (inetaddress ip,int port) using the specified IP and port to establish the socket object
Sorket (String host,int port) using the specified host and port to establish the socket object
The above two methods have three options for Boolean stream (Boolean indicates whether streaming communication is selected)
You can use the getInputStream and getoutstream of the socket class to read and write data input and output streams. But to do exception handling, read the input and output stream to establish a more easy-to-operate inputstreamreader and out ... Close (Socket) disconnects after communication ends.
Socket application:
Java Socket Communication