2016-07-28 99 views
0

我被要求設計以下編程問題。客戶端套接字連接到多個套接字和餘額加載到一個空閒套接字

以前,當客戶端向我的應用程序發送請求時,我需要將其路由到另一臺服務器上的特定端口。服務器會及時響應,並將響應從他們的服務器發送到我的服務器,並將信息發送給我的客戶端。這工作得很好,直到負載增加,我們意識到其他服務器不處理多線程調用。

我已經被另一個應用程序給了一組有限的端口,所以無論何時一個客戶端請求的負載進入我的應用程序,我必須在這些端口之間平衡負載,這樣,如果端口A不空閒,我發送客戶端請求到端口B,如果B不是空閒的,它將進入端口C. [我知道這不是一個正確的解決方案,管理層希望它以這種方式工作]

所有處理的呼叫都是同步的,所有端口來自應用程序X)必須始終保持開放。

我目前最大的問題是:

  1. 知道當一個端口是免費的。 (不等待響應)

  2. 如何將負載推到其他端口。

我需要一些指向哪裏去頭。 你能幫忙嗎?

到目前爲止我所做的是將多個套接字加載到一個SocketAddress數組中。

 Selector socketSelector = SelectorProvider.provider().openSelector(); 
     int interestSet = SelectionKey.OP_CONNECT | SelectionKey.OP_WRITE | SelectionKey.OP_READ; 
     List<SocketAddress> socketAddresses = FactorySockectConnection.getSocketInstances(); 

     for (SocketAddress socketAddress : socketAddresses) { 
      SocketChannel socket = SocketChannel.open(socketAddress); 
      socket.configureBlocking(false); 
      socket.register(socketSelector, interestSet); 
     } 
     System.out.println("Start"); 

     while (true) { 

      try { 
       socketSelector.select(); 

       Set<SelectionKey> keys = socketSelector.selectedKeys(); 
       Iterator<SelectionKey> keyIterator = keys.iterator(); 
       while (keyIterator.hasNext()) { 

        SelectionKey selectedKey = keyIterator.next(); 

        if (selectedKey.isConnectable()) { 
         SocketChannel connectChannel = (SocketChannel) selectedKey.channel(); 
         connectChannel.finishConnect(); 
        } 
        if (selectedKey.isWritable() && requestMessageByte != null) { 
         SocketChannel writeChannel = (SocketChannel) selectedKey.channel(); 
         ByteBuffer buf = ByteBuffer.wrap(requestMessageByte.getBytes()); 
         while (buf.hasRemaining()) { 
          writeChannel.write(buf); 
         } 
         requestMessageByte = null; 
        } 

        if (selectedKey.isReadable() && responseMessage == null) { 
         SocketChannel readChannel = (SocketChannel) selectedKey.channel(); 

         ByteBuffer readBuffer = ByteBuffer.allocate(1024); 
         readChannel.read(readBuffer); 
         responseMessage = new String(readBuffer.array()); 
        } 
        keyIterator.remove(); 
       } 

回答

0

我打算使用負載平衡器。我會及時向大家發佈。