客户端/服务器套接字:如何使服务器推送消息到客户端?
问题描述:
我目前正在Java中通过套接字进行通信的客户端/服务器应用程序。我对这种类型编程的经验相当有限,而且我只有从服务器类型的应用程序完成客户端/响应请求。现在,我想以相反的方式去做。也就是说,客户端连接到服务器,然后等待服务器定期向其发送消息。客户端/服务器套接字:如何使服务器推送消息到客户端?
问题是:我该如何去创建这样的应用程序?或者更重要的一点:如何在不首先接收请求的情况下让服务器写入客户端套接字,以及如何让客户端监听更多消息?
答
我认为你在混合客户端和服务器逻辑,你应该考虑你的服务器是否更像一个客户端。但行...
首先一些Java类作为切入点
您可以创建一个像
// 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);
+0
谢谢!将检查出来。 我知道我想要的是服务器行为的不寻常。服务器类型有两种模式,一种是连续向连接的客户端发送数据,另一种是接收请求的模式。我不会使用请求模式(或根本不使用)。 – benbjo 2013-03-06 10:51:50
你怎么能接收器不给送货地址的订单? – ericson 2013-03-06 10:52:18
客户端首先连接到服务器。这是他们做的唯一事情,除了稍后从服务器接收数据。 – benbjo 2013-03-06 11:14:43