1 回答
TA贡献1856条经验 获得超17个赞
一些东西:
这段代码将永远循环,直到客户端关闭连接:
while ((ch = server.getInputStream().read()) >= 0) {
System.out.println("Got byte " + ch);
}
然后在客户端关闭他的连接后,后续尝试向套接字发送“HELLO CLIENT”将产生一个 IO 异常。这将触发您的服务器循环退出。
简单的解决方法是调整您的协议,以便在某些标记字符上完成“消息”。在我的简单修复中,我只是将其调整为!在收到a 时爆发。
最好让每个客户端会话在 ioexception 而不是整个服务器块上终止。我对你的代码的重构:
public class ServerSideTCPSocket {
public void tryCloseSocketConnection(Socket socket) {
try {
socket.close();
}
catch(java.io.IOException ex) {
}
}
public void processClientConnection (Socket clientConnection) throws java.io.IOException {
int ch = 0;
while ((ch = clientConnection.getInputStream().read()) >= 0) {
System.out.println("Got byte " + ch);
if (ch == '!') {
break;
}
}
// Write to output stream
OutputStream out = clientConnection.getOutputStream();
String s = "HELLO CLIENT!";
byte[] bytes = s.getBytes("US-ASCII");
for (byte b : bytes) {
System.out.println(b);
out.write(b);
}
}
public void run() {
try {
int serverPort = 4023;
ServerSocket serverSocket = new ServerSocket(serverPort);
serverSocket.setSoTimeout(900000);
while (true) {
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket clientConnection = serverSocket.accept();
try {
System.out.println("Just connected to " + clientConnection.getRemoteSocketAddress());
processClientConnection(clientConnection);
}
catch (java.io.IOException ex) {
System.out.println("Socket connection error - terminating connection");
}
finally {
tryCloseSocketConnection(clientConnection);
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ServerSideTCPSocket srv = new ServerSideTCPSocket();
srv.run();
}
}
然后将您的客户端代码的消息调整为:
String s = "HELLO SERVER!"; // the exclamation point indicates "end of message".
添加回答
举报