[英]How to respond to a Web Services request via WebSockets
我在服务器和客户端之间建立了WebSockets连接。 这使我可以向客户端发送命令,然后客户端用数据响应我。 该服务器也具有Web服务。 然后,我可以说“在该客户端上执行此命令”。 因此,我们有:
Client1 --- webservices->服务器--- websockets ---> Client2
问题是,服务器上从Client2接收数据的方法无效 。
如何将数据发送回Client1?
网页服务:
@Path("/ws")
public class QOSResource {
public QOSResource(){}
@Produces(MediaType.TEXT_PLAIN)
@Path("/ping/{macAddr}")
@GET
public String getPing(@PathParam("macAddr") String macAddr){
return"Mac adresse : "+macAddr;
//WebSocketsCentralisation.getInstance().ping(macAddr);
}
}
的WebSockets
@OnWebSocketMessage
public **void** onText(Session session, String message) {
if (session.isOpen()) {
if(firstConnection){
firstConnection = false;
this.macAddr = message;
WebSocketsCentralisation.getInstance().join(this);
}
ObjectMapper mapper = new ObjectMapper();
Object o;
try {
o = mapper.readValue(message, Object.class);
if(o instanceof PingResult){
**// TODO return result to ws**
}
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
在此先感谢您的帮助
您在方法参数中获得的Session对象包含与远程端点进行对话的范围。
您将要使用Session.getRemote()返回的RemoteEndpoint来发送消息。
例子:
// Send BINARY websocket message (async)
byte data[] = mapper.toBytes(obj);
session.getRemote().sendBytesByFuture(data);
// Send TEXT websocket message (async)
String text = mapper.toString(obj);
session.getRemote().sendStringByFuture(text);
但是请注意,如果远程端点连接不再处于打开状态(例如,远程端点向您发送消息然后立即启动CLOSE握手控制消息的情况),则session.getRemote()调用将引发WebSocketException。 。
// How to handle send message if remote isn't there
try {
// Send message to remote
session.getRemote().sendString(text);
} catch(WebSocketException e) {
// WebSocket remote isn't available.
// The connection is likely closed or in the process of closing.
}
注意:这种使用websocket的样式,其中有一个Session和一个RemoteEndpoint,与即将发布的JSR-356标准( javax.websocket
)一致。 在标准API中,您将可以使用javax.websocket.Session
和javax.websocket.RemoteEndpoint
。
您的websocket处理程序应具有一个关联的Connection实例,可以在其上调用sendMessage()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.