你选择了一个很棒的学习练习,这是肯定的!
阅读这些内容,它们使用带有轮询的自定义路由器到路由器代理提供请求/回复的基本实现,并且应该解决您的客户端到设备问题。
该解决方案是同步的,因此从客户端发送的任何请求都会阻塞,直到它得到响应。就个人而言,我会为请求和回复使用异步以获得完全的灵活性,但该解决方案要复杂得多。但是,书中有一些示例称为Freelance
并Dealer/Router
说明了异步请求/回复。
这是同步多对多请求/回复的示例。你必须知道 ZeroMq 包络是如何工作的,才能完全理解这种方法的机制;请参见示例lbbroker1。
客户
setIdentity()
使用;设置客户端身份 对响应路由很重要。客户端循环发送对,等的
请求;如果设备存在,则从特定设备返回状态消息,否则,“无设备”返回给客户端。device1
device2
Socket client = context.socket(ZMQ.REQ);
client.setIdentity("client1".getBytes());
client.connect("tcp://localhost:5550");
for( int i = 0; i < 5; i++){
client.send("device" + i);
String reply = client.recvStr();
log("Received message: " + reply);
Thread.currentThread().sleep(1000);
}
设备
设备设置 id 就像客户端一样用于唯一路由。
设备发送device.send("DEVICEREADY")
到服务器以指示在线可用性。
设备执行recvStr()
3 次以从服务器读取完整的信封。
String deviceId = "device1"
Socket device = context.socket(ZMQ.REQ);
device.setIdentity(deviceId.getBytes());
device.connect( "tcp://localhost:5560");
device.send( "DEVICEREADY");
while (!Thread.currentThread().isInterrupted()) {
String clientAddress = device.recvStr();
String empty = device.recvStr();
String clientRequest = device.recvStr();
//create envelope to send reply to same client who made request
device.sendMore(clientAddress);
device.sendMore("");
device.send( "stauts on " + deviceId + " is ok");
}
服务器(路由器/路由器)
使用 ROUTER 套接字的自定义代理;客户端连接到前端路由器套接字,而设备连接到后端路由器。服务器在两个套接字上轮询消息。
Context context = ZMQ.context(1);
Socket frontend = context.socket(ZMQ.ROUTER);
Socket backend = context.socket(ZMQ.ROUTER);
frontend.bind( "tcp://localhost:5550");
backend.bind( "tcp://localhost:5560");
Poller poller = new Poller(2);
poller.register(frontend, Poller.POLLIN);
poller.register(backend, Poller.POLLIN);
while (!Thread.currentThread().isInterrupted()) {
poller.poll();
//frontend poller
if (poller.pollin(0)) {
String clientId = frontend.recvStr();
String empty = frontend.recvStr(); //empty frame
String deviceId = frontend.recvStr();
//if client is requesting to talk to nonexistent deviceId,
//return message "no device", otherwise, create envelope and send
//request on backend router to device.
if( deviceMap.get( deviceId) == null ){
frontend.sendMore(clientId);
frontend.sendMore("");
frontend.send("no deviceId: " + deviceId);
} else {
//request envelope addressed to specific device
backend.sendMore(deviceId);
backend.sendMore("");
backend.sendMore(clientId);
backend.sendMore("");
backend.send("hello from " + clientId);
}
}
//backend poller
if(poller.pollin(1)){
String deviceId = backend.recvStr();
String empty = backend.recvStr();
String clientId = backend.recvStr();
//device signaling it's ready
//store deviceId in map, don't send a response
if( clientId.equals("DEVICEREADY"))
deviceMap.put(deviceId, deviceId);
else {
//the device is sending a response to a client
//create envelope addressed to client, send on frontend socket
empty = backend.recvStr();
String reply = backend.recvStr();
frontend.sendMore(clientId);
frontend.sendMore("");
frontend.send(reply);
}
}
}