This is the fourth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

An overview

Before Java network programming (iii) — Socket-nuggets (juejin. Cn) introduced the client Socket. However, a client-side socket is not enough. A client is useless if you can’t talk to the server, so you need a server that waits for the client to connect. A server is like an operator sitting by the phone waiting for a call. They don’t know who will call or when, only that when the phone rings, they have to pick it up and talk to it, no matter who it is.

For servers that accept connections, Java provides a ServerSocket class representing the ServerSocket. In other words, the server Socket’s job is to sit by the phone and wait for the call. Technically, the server Socket runs on the server and listens for inbound TCP connections. Each server Socket listens on a specific port on the server machine. When a client on the remote host attempts to connect to this port, the server is woken up, negotiates to establish a connection between the client and server, and returns a regular Socket object representing the Socket between the two hosts. In other words, the server Socket waits for a connection, and the client Socket initiates the connection. Once the ServerSocket establishes a connection, the server sends data to the client using a regular Socket object. Data is always transferred over regular sockets.

Create the ServerSocket

There are four public ServerSocket constructors:

public ServerSocket(int port) throwsBindException, IOExceptionpublic ServerSocket(int port, int queueLength) throws BindException,IOException
public ServerSocket(int port,intQueueLength, InetAddress bindAddress) throws IOException
public ServerSocket(a) throws IOException
Copy the code

These constructors specify the port, the length of the queue to hold inbound connection requests, and the local network interface to bind.

Binding port

Using the no-argument constructor creates a ServerSocket object but does not bind it to a specific port, so it initially accepts no connections, but can then be bound using bind(). Java provides two functions for binding:

public void bind(SocketAddress endpoint) throws IOException
public void bind(SocketAddress endpoint, int queuelength) throws IOException
Copy the code

In this way, you can allow an application to set server socket options before binding ports, because some options are fixed after the server socket is bound:

ServerSocket ss = new ServerSocket();
/* Sets the socket option */
SocketAddress http = new InetSocketAddress(80);
ss.bind(http);
Copy the code

If null is passed in InetSocketAddress, any port will be selected.

Use ServerSocket

In Java, the server application lifecycle is:

  1. Use a ServerSocket() constructor to create a new ServerSocket on a particular port.
  2. ServerSocket listens for inbound connections to this port using its Accept () method. Accept () blocks until a client tries to establish a connection, at which point Accept () returns a Socket object that connects the client to the server.
  3. Depending on the type of server, the Socket’s getInputStream() and getOutputStream() methods are called to get input and output streams to communicate with the client.
  4. The server and client interact according to a negotiated protocol until the connection is closed.
  5. The server or client (or both) closes the connection.
  6. The server returns to Step 2 and waits for the next connection.

The following simple example is a time server whose socket listens on port 6666 and returns the time when a client socket connects.

public static void main(String[] args) throws Exception {
        ServerSocket server = null;
        try {
            server = new ServerSocket(6666);
            while (true) {
                Socket connection = null;
                try {
                    connection = server.accept();
                    Writer out = new OutputStreamWriter(connection.getOutputStream());
                    Date now = new Date();
                    out.write(now.toString() + "\r\n");
                    out.flush();
                    connection.close();
                } catch (IOException ex) {

                } finally {
                    try {
                        if(connection ! =null) connection.close();
                    } catch(IOException ex) { ex.printStackTrace(); }}}}finally {
            try {
                if(server ! =null)
                    server.close();
            } catch (IOException ex) {
            }
        }
    }
Copy the code

For space reasons, the rest of the ServerSocket (request queue length, ServerSocket shutdown, multi-threaded server) can be read in the next blog post.