[英](Java Multiclient server) No exception when client closes socket and server writes to client
服務器代碼:
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。 假設服務器會拋出異常?
任何幫助,將不勝感激。
PrintWriter
吞下異常。 請參閱Javadoc。 ServerSocket
之后調用setReuseAddress()
是完全沒有意義的,就像在循環中調用它一樣。 我認為您應該在完成一會兒時添加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.