1 回答

TA貢獻1856條經(jīng)驗 獲得超17個贊
一些東西:
這段代碼將永遠循環(huán),直到客戶端關(guān)閉連接:
while ((ch = server.getInputStream().read()) >= 0) {
System.out.println("Got byte " + ch);
}
然后在客戶端關(guān)閉他的連接后,后續(xù)嘗試向套接字發(fā)送“HELLO CLIENT”將產(chǎn)生一個 IO 異常。這將觸發(fā)您的服務器循環(huán)退出。
簡單的解決方法是調(diào)整您的協(xié)議,以便在某些標記字符上完成“消息”。在我的簡單修復中,我只是將其調(diào)整為!在收到a 時爆發(fā)。
最好讓每個客戶端會話在 ioexception 而不是整個服務器塊上終止。我對你的代碼的重構(gòu):
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();
}
}
然后將您的客戶端代碼的消息調(diào)整為:
String s = "HELLO SERVER!"; // the exclamation point indicates "end of message".
添加回答
舉報