How to specify message destination on the nodejs websocket? - node.js

I want to send messages from nodejs backend to the specified websocket channel. So I want to implement/use similar function like convertAndSend function on the spring SimpMessagingTemplate.
I try to implement this with ws lib, but the send function only has two parameter: message & callback and I cannot specify the message destination. Here is a brief example from backend code:
const wss = new WebSocket.Server({
port: 8081,
server: app,
path: '/ws',
/*...*/
});
/*...*/
wss.send(`chat-room/${roomId}`, JSON.stringify(message)); // I want to this
And here is a brief frontend code that works well:
/*...*/
this.rxStomp.configure({
brokerURL: 'ws://localhost:8081/ws',
/*...*/
});
this.rxStomp.activate();
/*...*/
return this.rxStomp.watch(`chat-room/${roomId}`);
So my question is: it is possible to specify message destination with ws or other libs on the nodejs? If yes then how?

I have not used 'Convert and send' or the 'Web Socket' module ( I use socket.io personally ) but the concept should be the same.
The basic flow is
User connects to socket server ( gets a socket ID assigned to them )
On an action, lets say 'joinroom' from the client app you execute a 'emit' command to the websocket server (this is socket.io syntax) eg
socket.emit('joinRoom',roomID,otherparams)
In the sample above, we are 'emitting' a request to our 'socket' server, in the above example 'socket' is the namespace for our socket connection, so socket.emit send the request to the socket server.
Our socket server has code to 'listen' for requests to 'joinRoom' using the 'on' syntax eg
socket.on('joinRoom',(roomID,otherparams)=>{
//perform action, eg. query DB for room chats etc
// once action is done, emit back to user
socket.in(roomID).emit(data)
})
In the above code, we have an 'on' event that is the 'listener' on the socket server, this will listen for 'emits' to this action, so from the client we ran an 'emit' to the socket server, the socket server found the action (on event) 'joinRoom' and ran the code, after the code was successful it then finds all users 'in' the room (roomID that was passed to the emit) and sends it to all 'sockets' that are 'in' that room
On your client, you too have 'on' listeners, so when the socket server 'emits' to the client(s) they are listening for those specific commands. Because the 'socket.in' only 'emits' to clients who are 'in' the room only those users get the new payload from the server
You app will continue in this fashion, emits and on events. This is the basic flow and can be built out for 1 to 1 chats, group chats etc

Related

Uncaught TypeError: socket.to is not a function

I want to emit some data to a room in socket.io.
According to the socket.io docs,
In one place (https://socket.io/docs/rooms-and-namespaces/#Joining-and-leaving) it is said,
io.to('some room').emit('some event');
And in another place (https://socket.io/docs/emit-cheatsheet/) it is said,
socket.to('some room').emit('some event', "description");
I tried both of these but got the error,
uncaught TypeError: io.to is not a function
and
uncaught TypeError: socket.to is not a function
All other socket.io functions i used worked except for this
I included
<script src="/socket.io/socket.io.js"></script>
in the head tag of the html file.
In the client side js file, i incuded
const socket = io.connect("http://localhost:3000/");
Also, I used socket.emit and it works the way it is supposed to.
Please tell me what is wrong with this..
If this Uncaught TypeError is happening on your client side, that's because io.to and socket.to are only server-side functions, and cannot be used on the client side. In the Client API part of the Socket.IO docs, it doesn't specify io.to and socket.to as valid API functions. Here is the client API docs.
And here is a snippet that you can use to emit to Socket.IO rooms:
Server
//Your code...
io.on("connection", socket => {
//Don't forget to do this!
socket.join("some room");
socket.on("some event", data => {
//Do socket.to if you want to emit to all clients
//except sender
socket.to("some room").emit("some event", data);
//Do io.to if you want to emit to all clients
//including sender
io.to("some room").emit("some event", data);
});
});
Client
//Remember to include socket.io.js file!
const socket = io.connect("http://localhost:3000");
socket.on("some event", data => { /* Whatever you want to do */ });
//To emit "some event"
//This will also emit to all clients in the room because of the way the server
//is set up
socket.emit("some event", "description");
If you need an explanation...
So what this does is, basically, since you can't emit to rooms on the client side (you can only emit to server), the client emits to the server, and the server emits the event to the room you want to emit to.
Hope this solves your problem :)
Step1: In the client-side js file, changes instead of io.connect("http://localhost:3000/") use given below line,
let io = require('socket.io').listen(server.listener);
Step2: You need to create a connection in (Both Client & serverSide) For the Testing purpose you can use check connection Establish or not Both End use can use Socket.io tester Chrome Extension.(https://chrome.google.com/webstore/detail/socketio-tester/cgmimdpepcncnjgclhnhghdooepibakm?hl=en)
step3: when a socket connection is Established in Both ends then you emit and listen to data Easily.
One thing when you listen to the data then sends Acknowledgement using Callback Function. I have Received data Successfully.
E.g.`
socket.on('sendMessage',async (chatdata,ack)=>{
ack(chatdata);
socket.to(receiverSocketId).emit('receiveMessage',chatdata);
});
`
yours, emitting a message is correct no need to change this one. But make sure and please check it again your socket connection is Establish successfully or not. another Shortcut way you can debug a code line by line you can easily resolve this problem.
I Hope using this approach you can resolve the Error, and it is help For a Future.
thanks:)

Using Socket.io with Sequelize

I am trying to use Socket.io and Sequelize to create a chat app. Socket.io will handle the socket to allow for instant messaging. Sequelize will handle storing the messages so when you refresh the screen you still have your messages.
What is happening is that on localhost my socket works, but it does not send the messages to the database. When I put it onto Heroku, my database worked, but it does not use the sockets.
My socket is located in app.js and my database route is located in routes/messages.js.
I have been working on this bug for a while now and I have been trying to get help with it. I think the best way to share this is with my markdown I created detailing my efforts to fix my bug that can be found at here. My repo for this can be found here.
There are a few different parts that you need to distinguish:
the HTTP server, in your code represented by the variable http
the Express app, represented by app
the Socket.IO server, represented by io
a Socket.IO (client) connection (see below)
The HTTP server directs "normal" HTTP requests to the Express app, which will handle them according to the middleware and routes that are set up. A router handler gets called with (at least) two arguments, generally called req and res, to represent the (incoming) HTTP request and the (outgoing) HTTP response.
The Socket.IO server gets to handle specific Socket.IO requests, which get sent to the server by the Socket.IO client (running in the browser). When such a client sets up a connection with the server, the connection event gets triggered on the server. Any handlers for this event will get passed an argument, generally called socket, that represents the (bidirectional) connection with that client.
That Socket.IO connection can receive messages (sent from the client running in the browser), which trigger events on the socket. You can install a handler to listen for particular messages (like "chat message"), which will receive, as argument, the data that was sent to it by the client.
The issue in your code seems to be with setting up everything to handle those chat messages. The correct setup order would be:
listen on the Socket.IO server for connection events
when such an event is received, add a listener for the chat message event on the connection
when such an event is received, write the data to the database.
In code:
// Listen for new client connections.
io.on('connection', function(socket) {
// Listen for the client to send a _"chat message"_ message.
socket.on('chat message', function(data) {
// Store the data in the database.
models.Messages.create({
message : data.message,
username : data.username
});
});
});
As you can see, req and res aren't available inside of those Socket.IO event handlers, because those are only used for normal HTTP requests.
Also, as opposed to HTTP, you don't necessarily have to send anything back to the client when you have received a message, so I left that part out. The handler above only writes the message data to the database (it also doesn't check for, or handle, errors, which eventually you should add).

Socket.io : How to handle/manage multiple clients requests and responses?

I am very eager to integrate Socket.io to my node.js project, but I have some confusions on how to properly use socket.io. I have been looking through documentations and tutorials, but I have not been able to understand some concepts on how socket.io works.
The scenario I have in mind is the following:
There are multiple clients C1, C2, ..., Cn
Clients emit request to the server R1,...,Rn
Server receives request, does data processing
When data-processing is complete, Server emits response to clients Rs1, .., Rs2
The confusion I have in this scenario is that, when the server has finished data processing it emits the response in the following way:
// server listens for request from client
socket.on('request_from_client', function(data){
// user data and request_type is stored in the data variable
var user = data.user.id
var action = data.action
// server does data processing
do_some_action(..., function(rData){
// when the processing is completed, the response data is emitted as a response_event
// The problem is here, how to make sure that the response data goes to the right client
socket.emit('response_to_client', rData)
})
})
But here I have NOT defined which client I am sending the response to!
How does socket.io handle this ?
How does socket.io make sure that: response Rs1 is sent to C1 ?
What is making sure that: response Rs1 is not sent to C2 ?
I hope I have well explained my doubts.
The instance of the socket object corresponds to a client connection. So every message you emit from that instance is send to the client that opened that socket connection. Remember that upon the connection event you get (through the onDone callback) the socket connection object. This event triggers everytime a client connects to the socket.io server.
If you want to send a message to all clients you can use
io.sockets.emit("message-to-all-clients")
and if you want to send an event to every client apart the one that emits the event
socket.broadcast.emit("message-to-all-other-clients");

socket.io client connection cannot be made on the 2nd time

Currently, I am implementing an API using nodejs express, then it needs to connect to socket.io and send event.
The API is located in socket.io-client (client), and it connects to socket.io (server)
1st API call: success
The connection is made for the 1st call of the API, message is sent and socket can be disconnected, with the 'disconnect' callback is invoked both on client and server side.
2nd API call: failure
When the API is invoked the 2nd time, the connection to server cannot be made, 'client' callback on client side is not called.
3rd API call: success
Then I tried to restart the client side, keeping other things unchanged. The API is called again, and the connection to socket.io is made successfully and everything is fine.
Can anyone explain the logistics behind this?
Updated
client.js
App.getByUserId(message.to_id, function(error, app) {
var socket = io.connect('http://127.0.0.1:9002');
socket.on('connect', function(){
console.log("client connect socket id:" + socket.id);
console.log("appkey:" + app.private_token);
socket.emit('appkey.check',{appkey: app.private_token, uuid: message.to_id.uuid}, function(data){
socket.emit("forceDisconnect");
socket = null;
});
});
You just hit one of Socket.IO's many "features" or "bugs" depending how you see this. Socket.IO tries to be smart and re-use connections (which causes a lot of connection issues actually) The way around this is use the force new connection option in your io.connect:
io.connect('http://127.0.0.1:9002', { 'force new connection': true });
What you could also do is use https://github.com/primus/primus which wraps Socket.IO if you use the socket.io transformer. Internally, it completely removes the use of the io.connect and uses the much more lower level io.Socket constructor to create more stable connections that you would get with a stock socket.io.
With socket 1.0+, you have to use this for forcing new connection.
io.connect(SERVER_IP, { 'forceNew': true });

Generating socket.io at Server side as Rest request

There is a way to manage the socket.io creation at Server Side?, Currently, I couldn't found any doc, Only found in relation with the socket is created per request from a client "io.connect(server)".
The current flow work OK:
Set Socket.io (at Node.js) at SERVER:PORT
Client connect to SERVER
using io.connect(SERVER:PORT)
I wonder if it is possible ? Trying to do:
Set Socket.io (at Node.js) at SERVER:PORT
Recieved a POST (REST) - Server side
Create/Open Socket.io a server side.
At response of Post send the id?
the clien open a socke.io
Sent to client socket.id to client as
So Far, looking in deep on the code and doc, I found that socket.io support namespaces, so I used this in order to manage client connection id.
at server.js
var app = express();
var server = require('http').createServer(app),
io = require('socket.io').listen(server,{ log: false });
// Rest New Process
function generateNameSpaceWs (responce, request) {
io.of("/" + id).on('connection', handler);
response.send(id);
}
app.post("/newWS", function (res, req) {
return generateNameSpaceWs(res, req);
}
at Client.js
function makeWS(){
var ws, c = new XMLHttpRequest();
c.open("GET", url, false);
c.send();
if (c.status == 200){
id = JSON.parse(c.responseText);
ws = new io.connect("server/" + id)
}
So far you are doing right, if I understand your question correctly, you are trying to authenticate connection via POST, so that user can only connect to server via socket if server responds to ID. This is a roundabout way. Use the socket instead of POST.
Socket server has to be running already, and accepts connection via io.sockets.on('connection'), at server you can choose whether to accept it or reject it ,do socket.disconnect('unauthorized') to close connection from server.
I would you suggest you do this :
Set Socket.io (at Node.js) at SERVER:PORT
Client connect to SERVER using io.connect(SERVER:PORT)
Send what you are sending in POST over socket.
Authenticate/Process on io.sockets.on('connection', function(socket) at server.
Close socket if unathorized.
Send back ID data to client.
This doesn't seem possible -- while the official documentation for socket.io is lacking, the documentation for the net module indicates that the only way to create a socket is to initiate it server side.
However, you can still achieve the desired effect by creating an id for the socket on the server to associate with the socket. That is,
Set Socket.io (at Node.js) at SERVER:PORT
Recieved POST (REST) - Server side
Create id (Note:This could be done before step 2)
At response of Post send the id!
Client connect to SERVER
using io.connect(SERVER:PORT)
The client sends the id to the server using something like
socket.emit("set_id",id)
The server recieves the id and associates it with the socket using something like
socket.on("set_id",function(id){
socket.set("id",id)
}
Now you can reference the socket using the id that you created!
Good luck!

Resources