我在服务器和客户机之间有一个WebSockets连接。这允许我向客户端发送命令,他用数据来响应我。服务器也有web服务。然后,我可以说,“在那个客户端上执行这个命令”。所以我们有:
Client1 --webservices-->服务器--websockets-> Client2
问题是,服务器上从Client2接收数据的方法是void。
如何将数据发回Client1?
WebServices:
@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();
}
}
}提前感谢您的帮助
发布于 2013-06-18 12:57:20
在方法参数中获得的会话对象包含与远程端点的对话范围。
为了发送消息,您需要使用Session.getRemote()返回的Session.getRemote()。
示例:
// 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);但是,请注意,如果远程端点连接不再处于打开状态(例如远程端点发送消息,然后立即启动密切握手控制消息),则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使用方式,其中您有一个会话和RemoteEndpoint是一致的即将到来的JSR-356标准(javax.websocket)。在标准API中,可以使用javax.websocket.Session和javax.websocket.RemoteEndpoint。
发布于 2013-06-18 11:56:44
websocket处理程序应该有一个关联的连接实例,您可以在该实例上调用sendMessage()。
https://stackoverflow.com/questions/17167686
复制相似问题