2016-07-28 81 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

我打算使用负载平衡器。我会及时向大家发布。