2012-12-31 204 views
-1

我正在實現一個簡單的聊天應用程序。 服務器必須偵聽多個客戶端,並且服務器必須將一個客戶端輸入的數據發送給連接到該服務器的所有客戶端。 我已經通過以下代碼實現了這一點。意外的是我得到了java.net.SocketException:套接字關閉。 任何人都可以解決這個異常,並告訴我必須修改代碼發送數據到所有客戶端。如何解決socketClosed異常

Client.java

import java.io.*; 
import java.net.*; 
import java.util.*; 
class Client { 
    public static void main(String args[]) { 
     try { 
     InetAddress addr = InetAddress.getByName("172.26.45.132"); 
     Socket skt = new Socket(addr, 1234); 
     PrintWriter out = new PrintWriter(skt.getOutputStream(),true); 
     BufferedReader br = new BufferedReader(new InputStreamReader(skt.getInputStream())); 
     Scanner sc = new Scanner(System.in); 
     String msg=""; 
     while (msg!="exit") { 
     msg= sc.next(); 
     out.println(msg); 
     System.out.println("from Server"+br.readLine()); 
} 
    br.close(); 
out.close(); 
    } 
    catch(Exception e) { 
    System.out.print("Whoops! It didn't work!\n"); 
    } 
} 
} 

Server.java

import java.io.*; 
    import java.net.*; 
    class Server { 
public static ListenClient clients[] = new ListenClient[3]; 
public static int clientCount = 0; 
public static void main(String args[]) { 
    try { 
    ServerSocket srvr = new ServerSocket(1234); 
    Socket skt; 
    System.out.print("Server has connected!\n"); 
    while(clientCount < 3){ 
    skt = srvr.accept(); 
    clients[clientCount] = new ListenClient(skt,clientCount); 
    Thread t = new Thread(clients[clientCount]); 
    clientCount++; 
    t.start(); 
    } 
    } 
    catch(Exception e) { 
System.out.println(e); 
    System.out.print("Whoops! It didn't work!\n"); 
    } 
    } 
} 

    class ListenClient extends Server implements Runnable{ 
Socket sc; 
int id; 
ListenClient(Socket sc, int id){ 
    this.sc=sc; 
    this.id = id; 
} 
public void run(){ 
    try{ 
     BufferedReader br = new BufferedReader(new InputStreamReader(sc.getInputStream())); 
     String msg=""; 
     while((msg=br.readLine())!=null) 
      { 
      PrintWriter clientsOut; 
      for(int j = 0 ; j<=clientCount-1; j++){ 
      clientsOut = new PrintWriter(clients[j].sc.getOutputStream(),true); 
      clientsOut.println(msg); 
      clientsOut.close(); 
      } 
     } 
    } 
    catch(Exception e){ 
     System.out.println(e); 
    } 
} 

}

回答

1

SocketClosedException意味着已關閉套接字,然後繼續使用它。關閉輸入或輸出流將關閉套接字和其他流。因此,在讀取輸入的循環內關閉輸出是沒有意義的。