In Java network programming, is there any way to keep the server open even if the client is closed?

Suppose we have a simple echo client / server pair in Java As far as I know, once one side of the socket is disconnected, the whole connection disappears

But what if I want the server to stay alive, even if the client dies? I hope to restore the disconnected connection

Echo server:

import java.net.socket;
import java.net.ServerSocket;

public class EchoServer {

    public static void main(String[] args) throws Exception {

        // create socket
        int port = 4444;
        ServerSocket serverSocket = new ServerSocket(port);
        System.err.println("Started server on port " + port);

        // repeatedly wait for connections,and process
        while (true) {

            // a "blocking" call which waits until a connection is requested
            Socket clientSocket = serverSocket.accept();
            System.err.println("Accepted connection from client");

            // open up IO streams
            In  in  = new In (clientSocket);
            Out out = new Out(clientSocket);

            // waits for data and reads it in until connection dies
            // readLine() blocks until the server receives a new line from client
            String s;
            while ((s = in.readLine()) != null) {
                out.println(s);
            }

            // close IO streams,then socket
            System.err.println("Closing connection with client");
            out.close();
            in.close();
            clientSocket.close();
        }
    }
}

Thank you for any tips

Solution

What you lack is the concept of "session" Think about the location of the server when some bits reach the "line" What about these? Using TCP / IP, some information already exists on the line, namely:

>SRC addr > SRC port > dest addr > destination port > and message payload itself > and some other things (such as sequence counters to ensure that 'packets' are not confused during transmission)

The server's operating system uses Src / dest addr / port information to determine whether this is an "ongoing conversation" It mainly considers the dest port (because the message has been sent to the machine itself through the Internet and firewall) to determine whether it is suitable for Java programs listening to the 'dest port' However, it uses the entire SRC addr / SRC port / dest addr / dest port to try to transfer payloads to your program in the order they are sent by the sender (this may not be the order they arrive because of interference with the Internet) Note that a single "message" may actually be split into multiple packets The TCP / IP stack of your operating system is doing some work for you

However, please note that in order to perform this function on your behalf, the operating system must invest some resources to "track the status of TCP / IP sessions" At least, for each group of port / addr Src / DeST, you need to have a counter for the last "packet" received, and some buffer space to save the packets until your program is ready to consume them, so move forward

Now, the problem faced by TCP / IP stack implementers is "how long should I keep this state"? Enough 10 seconds? 20 minutes? In some cases, the session must "time out" after not hearing from the client for a period of time If there are more packets to be sent in the sequence and the client starts sending them again, the server must be able to say "sorry, you sent some packets of previous messages 234, but I lost 1-233 packets because I haven't received them from you for some time. Can we start again“

So in this sense, there is no way to prevent the client from "disconnecting" Of course, if the client recovers and sends more data, you can continue to listen to the socket But you and your clients need a way to "choose where we leave"

In HTTP, this is implemented using 'session cookie' - a long unique string provided by the server to the client, and the client resends each new request (whether it occurs in the same TCP level session or not) This is an "application level session", and its life cycle is longer than that of TCP session

Now that you are writing an application, it sounds like you have some control over the mutual control ("agreement") between the client and the server, you can choose more about how to deal with what is a session, if the client 'disappears' (session timeout), and how both parties can recover and "continue from where we interrupted" (re-establish the session) Don't forget authentication!

As others say, it depends largely on what you want to achieve

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>