假设我们在
Java中有一个简单的Echo客户端/服务器对.据我了解,一旦套接字的一侧断开,整个连接就消失了.
但是,如果我希望服务器能够始终保持活力,即使客户端死亡,该怎么办呢?我希望能够恢复断开的连接.
回声服务器:
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();
}
}
}
任何提示赞赏谢谢