我目前正在编写一个多客户聊天程序,这是非常好的工作。我现在唯一的问题是如果它被强制关闭
我明白了:
java.net.SocketException: Connection reset
我相信(从周围看)这与没有正确关闭客户端中的流/套接字有关。然而,我已经尝试了这么多地方来关闭所有的东西,但我似乎无法弄清楚。有谁能给我指个方向吗?
这里是客户端:(没有GUI的东西)套接字和流被定义为属性。
public void connectToServer(){
try{
System.out.println("Waiting to connect");
s = new Socket("localhost", 16789);
System.out.println("Connected");
ClientThread ct = new ClientThread();
ct.start();
openStreams();
}
catch(EOFException eofe){
System.out.println("EOFException");
}
catch(IOException ioe){
System.out.println("IO Error");
}
}
public void openStreams(){
try {
//open input streams
InputStream in = s.getInputStream();
br = new BufferedReader(
new InputStreamReader(in));
//open output streams
OutputStream out = s.getOutputStream();
pw = new PrintWriter(
new OutputStreamWriter(out));
}
catch(ConnectException ce){
System.out.println("Could not connect");
}
catch(IOException ioe){
System.out.println("IO Error");
}
catch(NullPointerException npe){
System.out.print("Server offline");
System.exit(0);
}
}
public void closeStreams(){
try{
pw.close();
br.close();
s.close();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
public void sendMsg(){
String message = enterMsg.getText();
pw.println(message);
pw.flush();
}
public void showMsg(){
String show;
try{
while((show = br.readLine()) != null){
chatArea.append(show + " \n");
}
}
catch(IOException ioe){
chatArea.append("Error showing msg \n");
}
}
class ClientThread extends Thread {
public void run(){
showMsg();
closeStreams();
}
}
}
以及服务器所指向的带有错误的特定部分:
while( ( msg = br.readLine()) != null ){
System.out.print(msg);
// convert & send msg to client
for(PrintWriter pw : clients){
pw.println(userName + ":" + msg );
pw.flush();
}
}
发布于 2015-04-09 00:44:52
java.net.SocketException: Connection reset
最常见的原因是:
正确的恢复方法是关闭套接字并忘记该对等项,但这两者都是应用程序协议错误,应该进行调查。
这与未在客户端内正确关闭流/套接字有关
不,它不是。它与过早关闭它们有关,无论哪个对等点没有得到这个异常。
至于“正确关闭流”,只需关闭PrintWriter.
关闭Socket
的输入流或输出流就会关闭另一个流和套接字本身,您应该选择最外层的输出流/写入器来关闭,这样它就会被刷新。
https://stackoverflow.com/questions/29527755
复制