I am fairly new with Spring websocket. I have a simple demo below:
HandshakeInterceptor class:
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 class:
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 mapping 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 }));
}
Now i want to send a message to a specific user. I define each device have a deviceId, so i want to know:
- How to handshake with attributes, which will be send from client?
- How to send handshake attributes from client javascript?
- How to send message from server to client by handshake attributes?
Thank you for your attention.