server side:
io.of('/lobby').on('connection', function(client) {
setInterval(function(){
io.to(client.id).emit('message','test');
},2000);
});
client side:
var ioLobby = io.connect('127.0.0.1:9001/lobby');
ioLobby.on('message',function(data){
console.log(data);
});
I'm trying to send a message to a specific client in socket.io version 1.2.1. I've verified that the socket joins the default room on the server side, but its not being triggered on the client side. Any ideas?
The line io.to(client.id) will only work if that user has first joined a room with that same name. You need something like
io.on('connection', function(socket){
socket.join('some room');
});
and then you can call io.to
io.to('some room').emit('some event'):
I compromised and ended up using
socket.emit()
The only downside in comparison is requiring a ref to the socket you're emitting to.
Related
So, I am quite puzzled. I have a socket IO server that runs OK, and the HTML web client does connect to it. But, I can't emit anything. I'm using xampp to serve webpages, but does socket IO need to serve content for it to receive and send data? It's weird that I connect OK,but that's it, no emit function works.
Here's my code..
var io = require('socket.io')();
io.on('connection', function(client){ console.log("Connected OK."); io.emit('message',"data"); });
io.on('message', function(client){ console.log(client); });
io.listen(8080);
HTML
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script>
// Create SocketIO instance, connect
var socket = io.connect('http://localhost:8080');
// Add a connect listener
socket.on('connect', function() {
alert('Client has connected to the server!');
});
socket.on('message', function(event) {
console.log('Received message from client!', event);
});
</script>
The code above prints "Connected OK" to the NPM console, and it alerts "Client has connected to the server!", but that's it. So my question is, does the NPM server need to serve the HTML to work, or am I doing things wrong?. I use xampp because of PHP and MySQL.
UPDATE:## The server sends to client just fine, and the client tries to send data back, and the server receives the packet. But then it reports: " engine:polling transport discarded - closing right away +0ms". Is this normal?
I have a node.js server and I attached socket.io listener to it. The code is like this.
const server = new Hapi.Server();
server.connection({
"port": config.port
});
let io = socketio(server.listener);
io.on("connection", function(socket) {
console.log("A user connected");
socket.on("disconnect", function(){
console.log("A user disconnected");
});
// receive message from client
socket.on("client-server", function(msg) {
console.log(msg);
});
});
// somewhere to emit message
io.emit("server-client", "server to client message");
Normally I use the standard way to connect to the websocket server. An example is like this:
<!DOCTYPE html>
<html>
<head><title>Hello world</title></head>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('server-client', function(data) {document.write(data)});
socket.emit('client-server', 'test message');
</script>
<body>Hello world</body>
</html>
It works without issue. Now, my colleague wants to connect to the websocket server from his FME server. Based on his research, the only way he can use to connect to a websocket server is using a url like this:
ws://localhost:3000/websocket
My question is: is there a way to connect to socket.io server listener using this type of string?
If not, is there a way to create a websocket server with ws://host:port url and also attach it to my node.js server?
Or, is there a way to connect to socket.io listener in FME server?
To tell Socket.IO to use WebSocket only, add this on the server:
io.set('transports', ['websocket']);
And on the client add this:
var socket = io({transports: ['websocket']});
Now you can only connect to the WebSocket server using ws protocol.
Am not able to call socket-client listener using sails.sockets.js onConnect event on server side..
E.g
onConnect: function(session, socket) {
socket.on('chat message', function(msg){
console.log(msg);
console.log("socket.id: " + socket.id);
sails.sockets.broadcast(socket.id, 'chat message', {msg:msg});
});
}
Please let me know whats the correct way of calling back to your socket-client using socket-server events like onConnect..
If you are using standard sails.js socket library:
$(document).ready(function() {
io.socket.on('connect', function() {
});
io.socket.on('chat message', function(data) {
io.socket.post('/routeToAction', {
}, function(data, jwres) {
});
});
});
for newer version, you have to use config/bootstrap.js file for listen events
module.exports.bootstrap = function(cb) {
// handle connect socket first event executes after logged in
sails.io.on('connect', function (socket){
// store facebook token here
});
// handle custom listener for other stuff
sails.io.on('doSomeStuff', function (socket){
// check facebook token match with requested token
});
cb();
};
client : you can simple emit "doSomeStuff" after logged in with facebook and pass token with each request
Finally am become little expert in web sockets who knows back anf forth of push technoligy via websockets..
How to start with websockets :
Step 1: Choose any websocket framework for your application and install socket client on client side and socker server on server side with listeners(imp.).
Step 2: Once you are ready with socket setup on both sides then your client/browser will make a connection after every page load which is listened on server side via onConnect listener or event.
Step 3: Successfull connection on both sides giving you socket object which contains each client socket id which is managed at server side to either join any channel/room or just to make a broadcast or blast.
Remember:
i. Socket object is responsible for defining listeners on both client side and server side. Using socket object you can pass any data to listeners.
ii. Socket connection is very helpful when you trying to push data from client to server and vice-versa.
iii. You can make your small chatter tool with it once you understand as mentioned above.
Will share similar working snippet soon..
//onConnect event on server side
onConnect: function(session, socket) {
console.log("Socket Connect Successfully: " + socket.id );
socket.on('chatAgency', function(data){
sails.sockets.broadcast(data.agencyId,"chatAgency", {message:data.message,agencyId:session.agencyId});
});
},
Question is geared towards understanding how socket.io works.
If I have a server with multiple clients and the following function (pseudocode):
// Server-side
socket.emit('data-request', { some large object });
Does the server send the large data object to each of the clients or does it only send to clients that have a corresponding (function / event) ?
socket.on('data-request', function(data){blah blah blah});
No, what you're doing there would send a message to every single socket that is connected to the server, except the socket that is socket, if you want to broadcast to a specific room you would do
io.sockets.in('some room name').broadcast('some data')
if you want to broadcast to everyone in a specific room except the sender if the sender is in that room you would do
socket.broadcast.to('some room name').emit('some data');
First of all though you would probably need to create some rooms, in which case you would just do
someSocket.join('some room name')
Maybe something like this would help you out.
io.sockets.on('connection', function (socket) {
// let everyone know i'm here
socket.broadcast.emit('user connected');
socket.on('join-data-request-room', function(){
socket.join('data-request-room')
})
});
Now you could do this
io.sockets.in('data-request-room').broadcast('new data')
and it would send to each in that room, there are currently no one in that room, to add people in that room you would do something like this on the client (browser).
io.emit('join-data-request-room')
Now and only now will that "client" be in the room data-request-room
I haven't used socket.io in months so there may be some better ways I don't know.
The message will be sent to only the socket who is listening. The socket connection means you get one to one connection between server and client.
If you want to broadcast the same message to all the clients (except yourself):
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.broadcast.emit('user connected');
});
The broadcast gets called like this, and the implementation is in the adapter module.
If you require more specific message sending you could use the room concept, read more about rooms.
It is my understanding that the server has no way of knowing who is listening to what message types, but I'm not 100% certain, and I will continue to look for a reference. In the meantime, if you want to send to only certain clients, you should use rooms.
EDIT:
This simple experiment should give the answer:
//Server-side
socket.emit('data-request', { a: 100 });
...
//Client-side
socket.on('message', function(data){console.log(data)});
Listen for all messages. The client should receive the data-request message.
EDIT 2: Disregard my example code. It doesn't work.
I have a socket.io connection to connect to server and client,
It work fine.
Now when I try to reconnect it on disconnect from server it get connected but then socket.on('message' doesnt get fired any more.
I checked it from server side it is pushing that message.
Please suggest me some thing I am out of ideas now.
I am sure that problem is on client side socket.on message
Client side code
var socket = new io.Socket('some host name',{port:80,rememberTransport:true});
socket.on('connect', function(){
clearInterval(socketInterval);
});
socket.on('message', function(obj)
{
alert("meg from server");
});
socket.on('disconnect', function()
{
socketInterval=setInterval("socket.connect()",5000);
});
socket.connect();
I don't know node.js, but it looks like syntax error, haven't you forgot the right paratheses?
socket.on('connect', function(){
clearInterval(socketInterval);
});
socket.on('message', function(obj)
{
alert("meg from server");
});
socket.on('disconnect', function()
{
socketInterval=setInterval("socket.connect()",5000);
});
it would appear that the "problem" most likely is on the server side. The server has two ways to send messages to the client (emit and broadcast). If you are doing a one to one message, most people use emit. I am assuming that you built a chat server which stores the sessionIds of the client. It works fine with the initial connection because the server has the correct sessionId, but let's say connection is lost and you reestablish connection, now the server tries to send a message to the client. If your server stored the initial sessionId, say in an array, and attempts to use the original sessionId to emit a message, it will fail because reconnection causes a new sessionId to be created.
The solution in this case is to remove the previous sessionId from the array and add the new sessionId upon reconnection.