【发布时间】:2015-04-09 00:36:47
【问题描述】:
我目前正在编写一个运行良好的多客户端聊天程序。我现在唯一遇到的问题是它是否被强制关闭
我明白了:
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();
}
}
【问题讨论】:
标签: sockets client-server printwriter