服务器代码:
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
}
当客户端连接到服务器时,服务器开始打印。但是当客户端关闭套接字时,服务器仍然保持println。假设服务器会抛出异常?
任何帮助都将不胜感激。
答案 0 :(得分:1)
PrintWriter
吞下例外情况。见Javadoc。setReuseAddress()
之后调用ServerSocket
完全没有意义,就像在循环中调用它一样。答案 1 :(得分:0)
我认为你应该在完成片刻时添加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();