2016-01-10 109 views
1

試圖編寫一個簡單的服務器來回顯文本,需要給它多個線程。每當客戶端連接時,我都會收到一個套接字。我不太清楚最新的錯誤,我只是剛剛開始學習,所以我不懂。如果任何人都可以告訴我什麼是錯的,我會很感激。 注意:這段代碼顯然不是完全完成的,我大多隻需要解決上述問題。閉合插座問題

import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.BufferedReader; 

import java.io.OutputStream; 
import java.io.PrintStream; 

import java.net.ServerSocket; 
import java.net.Socket; 

import java.io.IOException; 

public final class EchoServer 
{ 
    public static void main(String[] args) throws Exception 
    { 
     try (ServerSocket serverSocket = new ServerSocket(22222)) 
     { 
      while (true) 
      { 
       try (Socket socket = serverSocket.accept()) 
       { 
        Thread newThread = new Thread(new server(socket)); 
        newThread.start(); 
       } 
      } 
     } 
    } 
} 
class server implements Runnable 
{ 
    Socket mySocket; 
    server(Socket s) 
    { 
     mySocket = s; 
    } 

    public void run() 
    { 
     //while(true) 
     //{ 
      try 
      { 
       System.out.println("Client connected "); 

       InputStream is = mySocket.getInputStream(); 
       InputStreamReader isr = new InputStreamReader(is, "UTF-8"); 
       BufferedReader br = new BufferedReader(isr); 

       OutputStream os = mySocket.getOutputStream(); 
       PrintStream out = new PrintStream(os); 

       String input = ("..."); 

       while(!input.equals("exit")) 
       { 
        input = br.readLine(); 
        out.println("Server> " + input); 
       } 
      } 
      catch(IOException e) 
      { 
       System.out.println(e); 
      } 
     //} 
    } 
} 
+0

你應該閱讀,直到'br.readLine()'返回'null' –

回答

2

嘗試,與資源塊時,都會立刻退出關閉資源,所以

try (Socket socket = serverSocket.accept()) 
{ 
    Thread newThread = new Thread(new server(socket)); 
    newThread.start(); 
} 
// socket is closed by here, but newThread may still be running. 

所以,只是刪除try

Socket socket = serverSocket.accept(); 
Thread newThread = new Thread(new server(socket)); 
newThread.start(); 
// socket is still open here. 

但記得要關閉套接字在你的server類(最終)。

+0

...所以刪除'try'塊。 –

+0

@PeterLawrey謝謝,更新。 –