How to use websocket in spring boot and react js? - spring-boot

I referred to this spring boot doc to create web socket in spring boot.
I used stompjs and sockjs-client
var socket = new SockJS('/gs-guide-websocket');
//gives an error in below line
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function (greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
});

use this stompjs and socket-client
then import them
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
to connect websocket
//use your link here
var sock = new SockJS('http://localhost:8102/api/ws');
let stompClient = Stomp.over(sock);
sock.onopen = function() {
console.log('open');
}
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/public', function (greeting) {
console.log(greeting);
//you can execute any function here
});
});

Related

SockJS doesn't set Bearer authorization token when making handshake

I have a spring boot + angularjs application, i configured it to have a socket connection. this is my socket controller in angularjs:
function SocketController($timeout, localStorageService) {
var vm = this;
var accessToken = localStorageService.get('accessToken');
var stompClient;
// i can see valid value of token in console
console.log(accessToken)
if (accessToken) {
var socket = new SockJS('/looping',
null,
{
transports: ['xhr-streaming'],
headers: {'Authorization': 'Bearer ' + accessToken}
});
stompClient = Stomp.over(socket);
stompClient.connect({"X-Authorization": "Bearer " + accessToken}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/loops', function (message) {
console.log(message);
});
});
} else {
console.log("token expired");
}
function sendEvent(loopId, value) {
if (stompClient != null) {
stompClient.send("/topic/loops", {}, JSON.stringify({'loopId': new Date(), 'value': 'hey silver'}));
}
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
stompClient = null;
}
console.log("Disconnected");
}
}
now, the problem is that when i check request headers in firefox devtools, authorization header doesn't set as you can see below:
How can i solve this problem? I'm new to socket.
UPDATE
When i edited the request using firefox devtools and set Authorization header in request headers, received response with 200 status code but the response content in html of index.html !

How do I subscribe a web socket end point in kotlin

I create my spring boot web socket according to the doc and how can I subscribe this end point in kotlin.
#MessageMapping("/chat")
public void chatNotice() {
simpMessagingTemplate.convertAndSend("/topic/chat");
}
Is there a way to subscribe like in js
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/chat', function (greeting) {
console.log(greeting);
});
});
If I use okhttp,
override fun onMessage(webSocket: WebSocket?, text: String?) {
output("Receiving : " + text!!)
}
but how can I subscribe an end point?

How to handle Stomp JS disconnect in Spring MVC?

In the project I've been working on, I found a problem with Stomp JS client disconnect.
It's about a case when user closes the tab in browser or when there's a problem with internet connection. In other words, I want to be able to handle this disconnect java side (server side). Is it possible?
I already have code that handles Websocket opening and it works fine, what I want to achieve is to handle connection closing (both expected and unexpected cases)
Here's a piece of my HTML file that includes Stomp JS related code (I can provide Java code as well if it's necessary):
<script type="text/javascript">
$(document).ready(function() {
connect();
});
var stompClient = null;
function connect() {
var socket = new SockJS('/lock-document');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/notify-open-documents/${id}', function (messageOutput) {
console.log('Receiving message: ' + JSON.parse(messageOutput.body));
});
sendName();
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
console.log("Disconnected");
}
function sendName() {
console.log("Sending message : " + JSON.stringify({'documentId' : "${id}" }));
stompClient.send('/ws/lock-document', {}, JSON.stringify({'documentId': "${id}"}));
}
</script>

Spring websocket Server and unity3d client

i'm using the spring web socket , it's a chat web socket app, every user msg will be delivered to all users, this below my home.html
function connect() {
var socket = new SockJS('http://192.168.1.115:8080/ROOT/hello');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function(greeting) {
console.log(greeting);
console.log("greetinggggggggg");
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendName() {
var name = document.getElementById('name').value;
stompClient.send("/app/hello", {}, JSON.stringify({
'name' : name
}));
}
I want to use a unity3d app as client, actually i'm using socket io to connect to a web socket endpoint.
socket io link on assets store https://www.assetstore.unity3d.com/en/#!/content/21721
i could connect to the endpoint but i could not find how to subscribe to /topic/greetings as
stompClient.subscribe('/topic/greetings', function(greeting){
console.log(greeting);
console.log("greetinggggggggg");
showGreeting(JSON.parse(greeting.body).content);
});
});
Thanks

Difference between io.on and socket.on in Socket.io?

I am confused on what the 'socket' parameter is that is passed with the function (In 'The enigma' section). Then the parameter gets used 'socket.on'. What is the difference between io.on and socket.on?
The following code is slightly adapted from the Socket.io chat application example.
Variables
var http = require('http');
var express = require('express');
var app = express();
var server = http.createServer(app)
var io = require('socket.io').listen(server);
The enigma
io.on('connection', function (socket) {
console.log('user connected');
socket.on('message', function(msg) {
console.log('message: ' + msg);
io.emit('message', msg);
})
});
Start server
server.listen(3000, function() {
console.log('server is running');
});
index.jade
body
script(src="/socket.io/socket.io.js")
form(method='post', action="/")
input(type='text', id='user', autocomplete='off')
input(type='submit', onClick="myFunc()")
strong messages:
p(id="messages")
script.
var socket = io();
socket.on('message', function(msg) {
console.log('client: ' + msg);
});
function myFunc() {
var text = document.getElementById('user');
socket.emit('message', text.value);
text.value = '';
};
In your code example, io is a Socket.IO server instance attached to an instance of http.Server listening for incoming events.
The socket argument of the connection event listener callback function is an object that represents an incoming socket connection from a client.
Both of them can listen for events with the on method.
It might help you visually understand how the two are separate if you re-imagine your code sample like this:
var connectionEvent = function(socket) {
console.log('user connected');
socket.on('message', function(msg) {
console.log('message: ' + msg);
io.emit('message', msg);
});
};
io.on('connection', connectionEvent);

Resources