我對編程非常陌生,特別是對於套接字編程。我試圖弄清楚通信是如何工作的(不是我所有的書籍),但是立即用下載的SimpleEchoServer示例立即運行到我的第一個問題。 Communicationflow可以工作,但是當Clientsocket關閉他的連接而不發送特定的字符串時,我的服務器就會崩潰。你能告訴我我做錯了什麼嗎?客戶端關閉連接後Java TCPSocket中斷
這是服務器端:
import java.net.*;
import java.io.*;
import java.net.InetAddress;
public class EchoServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
Integer port = new Integer(args[0]);
try {
serverSocket = new ServerSocket(port);
}
catch (IOException e) {
System.err.println("Could not listen on port: "+port);
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection on port "+port+" ...");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println ("received: " + inputLine);
out.println(inputLine);
if (inputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
,這就是客戶端
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
String serverHostname = new String (args[0]);
Integer port = new Integer(args[1]);
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " + serverHostname + " on port 10007.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream(), "UTF-8"));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.print ("input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
System.out.print ("input: ");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
您面臨的問題與此處所述的問題非常相似。 http://stackoverflow.com/questions/28387210/java-closing-client-socket-resets-server-socket/28387292#comment45112177_28387292 – h7r 2015-02-07 22:41:33
謝謝,我現在就讀這個。首先我想說我也嘗試了多線程回聲螞蟻,它在3次請求後中斷。第一個被接受,secont凍結了我的服務器控制檯,第三個打破了與客戶端控制檯中的套接字 - 重置消息的連接 – dumbashell 2015-02-07 22:50:42
好的,謝謝,我明白了:D – dumbashell 2015-02-07 23:10:55