2013-03-06 140 views
1

我目前正在Java中通過套接字進行通信的客戶端/服務器應用程序。我對這種類型編程的經驗相當有限,而且我只有從服務器類型的應用程序完成客戶端/響應請求。現在,我想以相反的方式去做。也就是說,客戶端連接到服務器,然後等待服務器定期向其發送消息。客戶端/服務器套接字:如何使服務器推送消息到客戶端?

問題是:我該如何去創建這樣的應用程序?或者更重要的一點:如何在不首先接收請求的情況下讓服務器寫入客戶端套接字,以及如何讓客戶端監聽更多消息?

+0

你怎麼能接收器不給送貨地址的訂單? – ericson 2013-03-06 10:52:18

+0

客戶端首先連接到服務器。這是他們做的唯一事情,除了稍後從服務器接收數據。 – benbjo 2013-03-06 11:14:43

回答

1

我認爲你在混合客戶端和服務器邏輯,你應該考慮你的服務器是否更像一個客戶端。但行...

首先一些Java類作爲切入點

AbstractSelector

SocketChannel

您可以創建一個像

 // Create a new selector 
     Selector socketSelector = SelectorProvider.provider().openSelector(); 

     // Create a new non-blocking server socket channel 
     mServerChannel = ServerSocketChannel.open(); 
     mServerChannel.configureBlocking(false); 

     // Bind the server socket to the specified address and port 
     InetSocketAddress isa = new InetSocketAddress(mHostAddress, mPort); 
     mServerChannel.socket().bind(isa); 



     // Register the server socket channel, indicating an interest in 
     // accepting new connections 
     mServerChannel.register(socketSelector, SelectionKey.OP_ACCEPT); 

選擇一個新的選擇可以等待用於啓動客戶端連接

// Wait for an event one of the registered channels 
mSelector.select(); 

並且在連接新客戶端後,AbstractSelector可用於向客戶端發送響應。

socketChannel.write(buf); 

示例代碼: http://rox-xmlrpc.sourceforge.net/niotut/

+0

謝謝!將檢查出來。 我知道我想要的是服務器行爲的不尋常。服務器類型有兩種模式,一種是連續向連接的客戶端發送數據,另一種是接收請求的模式。我不會使用請求模式(或根本不使用)。 – benbjo 2013-03-06 10:51:50

相關問題