Socket主要有两个类:
- java.net.Socket (客户端)
- java.net.ServerSocket (服务器端)
1。 the Socket class
A socket is an endpoint of a network connection. A socket enables an application to read from and write to the network. Two software applications residing on two different computers can communicate with each other by sending and receiving byte streams over a connection. To send a message from your application to another application, you need to know the IP address as well as the port number of the socket of the other application. In Java, a socket is represented by the java.net.Socket class.
To create a socket, you can use one of the many constructors of the Socket class. One of these constructors accepts the host name and the port number:
public Socket (java.lang.String host, int port)
new Socket ("yahoo.com", 80);
2。 The ServerSocket Class
The Socket class represents a "client" socket, i.e. a socket that you construct whenever you want to connect to a remote server application. Now, if you want to implement a server application, such as an HTTP server or an FTP server, you need a different approach. This is because your server must stand by all the time as it does not know when a client application will try to connect to it. In order for your application to be able to stand by all the time, you need to use the java.net.ServerSocket class. This is an implementation of a server socket.
ServerSocket is different from Socket. The role of a server socket is to wait for connection requests from clients. Once the server socket gets a connection request, it creates a Socket instance to handle the communication with the client.
To create a server socket, you need to use one of the four constructors the ServerSocket class provides. You need to specify the IP address and port number the server socket will be listening on. Typically, the IP address will be 127.0.0.1, meaning that the server socket will be listening on the local machine. The IP address the server socket is listening on is referred to as the binding address. Another important property of a server socket is its backlog, which is the maximum queue length of incoming connection requests before the server socket starts to refuse the incoming requests.
One of the constructors of the ServerSocket class has the following signature:
public ServerSocket(int port, int backLog, InetAddress bindingAddress);
InetAddress.getByName("127.0.0.1");
new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));