How do I subscribe a web socket end point in kotlin - spring-boot

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?

Related

How to use websocket in spring boot and react js?

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
});
});

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

Call SignalR Server Method in javascript function without event

I have a SignalR Server Method as mentioned below. I was able to call the method inside
public void AddNotification(string message, string toUser)
{
lock (connectedUsers)
{
if (connectedUsers.ContainsKey(toUser))
{
string receiverID = connectedUsers[toUser];
hubContext.Clients.Client(receiverID).addMessage(message);
}
}
}
I was able to call the method from javascript using JS Client.
$(function () {
$("#sendControls").hide("fast");
$.connection.hub.url = 'http://localhost:45210/signalr/hubs';
// Proxy created on the fly
selfHostHub = $.connection.selfHostHub;
// Declare a function on the hub so the server can invoke it
selfHostHub.client.addMessage = function (message) {
$('#messages').append("<li>" + message + "</li>");
};
// Start the connection
$.connection.hub.start().done(function () {
$("#Endcall").click(function () {
selfHostHub.server.addNotification(username + " has disconnected call for loanid " + loanid, supervisorName);
});
});
});
Is it possible to call Server method inside javascript function and instead of OnClick event. Kindly provide with any solution.

How to use WebSockets broadcast for play framework 1.2.7

My code can work.But only refresh a page of one window.
If I open window1 and window2 , both open websocket connect.
I keyin word "test123" in window1, click sendbutton.
Only refresh window1.
How to refresh window1 and window2 ?
Client
<script>
window.onload = function() {
document.getElementById('sendbutton').addEventListener('click', sendMessage,false);
document.getElementById('connectbutton').addEventListener('click', connect, false);
}
function writeStatus(message) {
var html = document.createElement("div");
html.setAttribute('class', 'message');
html.innerHTML = message;
document.getElementById("status").appendChild(html);
}
function connect() {
ws = new WebSocket("ws://localhost:9000/ws?name=test");
ws.onopen = function(evt) {
writeStatus("connected");
}
ws.onmessage = function(evt) {
writeStatus("response: " + evt.data);
}
}
function sendMessage() {
ws.send(document.getElementById('messagefield').value);
}
</script>
</head>
<body>
<button id="connectbutton">Connect</button>
<input type="text" id="messagefield"/>
<button id="sendbutton">Send</button>
<div id="status"></div>
</body>
Play Framework WebSocketController
public class WebSocket extends WebSocketController {
public static void test(String name) {
while(inbound.isOpen()) {
WebSocketEvent evt = await(inbound.nextEvent());
if(evt instanceof WebSocketFrame) {
WebSocketFrame frame = (WebSocketFrame)evt;
System.out.println("received: " + frame.getTextData());
if(!frame.isBinary()) {
if(frame.getTextData().equals("quit")) {
outbound.send("Bye!");
disconnect();
} else {
outbound.send("Echo: %s", frame.getTextData());
}
}
}
}
}
}
You have the basic of making work a single socket. However, each socket you are creating uses your socket events. Since each of the sockets would equal a thread, you need to send the event for each socket you can have. This is why when a new socket is open you need to map it in an array of sockets.
This thread can help you out.
Websocket send data all client in playframework 2
And refer to this exemple of play with framework.
https://github.com/playframework/playframework/blob/master/samples/java/websocket-chat/app/models/ChatRoom.java#L89

Resources