假设我们在Java中有一个简单的Echo客户机/服务器对。据我所知,一旦插座的一侧断裂,那么整个连接就会消失。
但是,如果我想要一个即使客户端死机也能始终保持活动状态的服务器呢?我希望能够恢复断开的连接。
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();
}
}
}感谢您的任何建议
发布于 2016-02-28 04:04:13
正如有人指出的,使用TCP不能做到这一点。
下面是一个简单的DatagramSocket (UDP)回显服务器示例。
package test;
import java.io.*;
import java.net.*;
public class UDPEchoServer {
public static void main(String[] args) throws IOException
{
new ServerThread().start();
}
static class ServerThread extends Thread
{
protected DatagramSocket socket = null;
public ServerThread() throws IOException
{
this("ServerThread");
}
public ServerThread(String name) throws IOException
{
super(name);
socket = new DatagramSocket(4444);
}
public void run()
{
try {
while (true) {
byte[] buf = new byte[256];
// receive data
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// send back the response to the client at "address" and "port"
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
}
}
catch (IOException e) {
e.printStackTrace();
}
socket.close();
}
}
}更新:添加了测试信息
您可以使用nc测试它
[gustaf@gustf-air]$ nc -u 127.0.0.1 4444
testing echo server
testing echo server
killing it now
killing it now
^C
[gustaf@gustf-air]$ nc -u 127.0.0.1 4444
now we are back
now we are backhttps://stackoverflow.com/questions/31531422
复制相似问题