2016-04-26 50 views
-2

如何創建一個接受輸入套接字的服務器,然後將它們輸入到一個隊列中(而不是在每個套接字上設置線程)?如何接受一個沒有在java中設置線程的套接字?

這裏是正規多線程的代碼(這裏將創建每一個插座的線程,但我想每一個我接受插座,將進入隊列,而無需每一個插座創建線程):

public class MultiThreadedServer implements Runnable{ 

    int   serverPort = 10000; 
    ServerSocket serverSocket = null; 

    public MultiThreadedServer(int port){ 
     this.serverPort = port; 
    } 

    public void run(){ 

     try { 
      this.serverSocket = new ServerSocket(this.serverPort); 
     } catch (IOException e) { 
      throw new RuntimeException("Cannot open port 10000", e); 
     } 
     while(true){ 
      Socket clientSocket = null; 
      try { 
       clientSocket = this.serverSocket.accept(); 
      } catch (IOException e) { 
       throw new RuntimeException(
        "Error accepting client connection", e); 
      } 
      new Thread(new WorkerRunnable(clientSocket, "Multithreaded Server")).start(); 
     } 
    } 

謝謝

+1

查看你創建'Thread'的部分?將其替換爲將套接字放入隊列的部分。 – Kayaman

+0

嘗試Java NIO,您可以在其中執行多路複用(和非阻塞)io。 https://en.wikipedia.org/wiki/Non-blocking_I/O_%28Java%29 –

+0

@Kayaman,新線程的創建與套接字的接受同時發生? 如果我將在套接字請求到達時創建線程,會發生什麼情況? – adi

回答

0

如果我正確理解你的問題,這段代碼應該完成你想要的。

public class MultiThreadedServer implements Runnable 
{ 

    int serverPort = 10000; 
    ServerSocket serverSocket = null; 

    ArrayList<Socket> socketQueue; //ArrayList to be used as a queue 

    public MultiThreadedServer(int port) 
    { 
     this.serverPort = port; 

     socketQueue = new ArrayList<>(); //Initialize your ArrayList 
    } 

    public void run() 
    { 
     try 
     { 
      this.serverSocket = new ServerSocket(this.serverPort); 
     } 

     catch (IOException e) 
     { 
      throw new RuntimeException("Cannot open port 10000", e); 
     } 

     while(true) 
     { 
      Socket clientSocket = null; 

      try 
      { 
       clientSocket = this.serverSocket.accept(); 
      } 

      catch (IOException e) 
      { 
       throw new RuntimeException("Error accepting client connection", e); 
      } 

      socketQueue.add(clientSocket); //Add your newly accepted socket to ArrayList 
      //new Thread(new WorkerRunnable(clientSocket, "Multithreaded Server")).start(); 
     } 
    } 
} 

每次接受新連接時,它都會被添加到socketQueue(ArrayList)中。