[英](Java Multiclient server) No exception when client closes socket and server writes to client
Server code: 服务器代码:
public class Main {
public static void main(String args[]){
Socket s=null;
ServerSocket ss2=null;
System.out.println("Server Listening......");
try{
ss2 = new ServerSocket(8080);
}
catch(IOException e){
e.printStackTrace();
System.out.println("Server error");
}
while(true){
try{
s = ss2.accept();
ss2.setReuseAddress(true);
System.out.println("connection Established");
ServerThread st=new ServerThread(s);
st.start();
}
catch(Exception e){
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
}
class ServerThread extends Thread{
String line; = "testing";
PrintWriter os=null;
Socket s=null;
public ServerThread(Socket s){
this.s=s;
}
public void run() {
try{
os=new PrintWriter(s.getOutputStream());
}catch(IOException e){
System.out.println("IO error in server thread");
}
try {
for (int i = 0 ; i < 100 ; i++){
os.println(line);
os.flush();
Thread.sleep(1000);
}
}
catch(NullPointerException | IOException | InterruptedException e){
System.out.println("Client "+line+" Closed");
}
finally{
try{
System.out.println("Connection Closing..");
if(os!=null){
os.close();
System.out.println("Socket Out Closed");
}
if (s!=null){
s.close();
System.out.println("Socket Closed");
}
}
catch(IOException ie){
System.out.println("Socket Close Error");
}
}//end finally
}
When a client connects to the server, the server starts to println. 当客户端连接到服务器时,服务器开始打印。 But when the client closes socket, the server still keeps println.
但是当客户端关闭套接字时,服务器仍保留println。 Suppose the server will throw exception?
假设服务器会抛出异常?
Any help would be appreciated. 任何帮助,将不胜感激。
PrintWriter
swallows exceptions. PrintWriter
吞下异常。 See the Javadoc. setReuseAddress()
after the ServerSocket
has been bound is completely pointless, as is calling it inside the loop. ServerSocket
之后调用setReuseAddress()
是完全没有意义的,就像在循环中调用它一样。 I think you should add ss2.close()
and s.close()
when you finish the while 我认为您应该在完成一会儿时添加
ss2.close()
和s.close()
while(true){
try{
s = ss2.accept();
ss2.setReuseAddress(true);
System.out.println("connection Established");
ServerThread st=new ServerThread(s);
st.start();
}
catch(Exception e){
e.printStackTrace();
System.out.println("Connection Error");
}
}
ss2.close();
s.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.