我对 Spring websocket 相当陌生。我在下面有一个简单的演示:
HandshakeInterceptor 类:
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
private static final Log logger = LogFactory
.getLog(HandshakeInterceptor.class);
@Override
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
logger.info("Before Handshake");
return super.beforeHandshake(request, response, wsHandler, attributes);
}
@Override
public void afterHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {
logger.info("After Handshake");
super.afterHandshake(request, response, wsHandler, ex);
}
}
WebsocketEndPoint 类:
public class WebsocketEndPoint extends TextWebSocketHandler {
private static final Log logger = LogFactory
.getLog(WebsocketEndPoint.class);
@Override
protected void handleTextMessage(WebSocketSession session,
TextMessage message) throws Exception {
super.handleTextMessage(session, message);
logger.info("Recieved Message: " + message.getPayload());
TextMessage returnMessage = new TextMessage(message.getPayload()
+ " received at server");
logger.info("Return Message: " + returnMessage.getPayload());
session.sendMessage(returnMessage);
}
}
Spring映射websocket:
<bean id="websocket"
class="com.n9.api.websocket.handler.WebsocketEndPoint" />
<websocket:handlers>
<websocket:mapping path="/websocket" handler="websocket" />
<websocket:handshake-interceptors>
<bean
class="com.n9.api.websocket.HandshakeInterceptor" />
</websocket:handshake-interceptors>
</websocket:handlers>
html:
function connect() {
if ('WebSocket' in window){
console.log('Websocket supported');
socket = new WebSocket('ws://localhost:8080/n9-api/websocket');
console.log('Connection attempted');
socket.onopen = function(){
console.log('Connection open!');
}
socket.onclose = function(){
console.log('Disconnecting connection');
}
socket.onmessage = function (evt)
{
var received_msg = evt.data;
console.log(received_msg);
console.log('message received!');
}
} else {
console.log('Websocket not supported');
}
}
function disconnect() {
setConnected(false);
console.log("Disconnected");
}
function sendMessage(message) {
socket.send(JSON.stringify({ 'message': message }));
}
现在我想向特定用户发送消息。我定义每个设备都有一个 deviceId,所以我想知道:
- 如何与客户端发送的属性握手?
- 如何从客户端 javascript 发送握手属性?
- 如何通过握手属性将消息从服务器发送到客户端?
感谢您的关注。