What is socket variable in socket.io - javascript

I'm new to Node.js and socket.io.
I go official site of socket.io, and try a tutorial.
http://socket.io/get-started/chat/
It work correctly on my computer. But I can't understand essence of its code at all.
QUESTION:what is "socket variable" in below code. And Where is it from?
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
Maybe "msg variable" is String type variable. And it is from client side, right?

The socket variable is basically a socket to a client. The io.on('conection') will be called each time a new client connects and give a socket to subscribe to.
socket.on('chat message' will subscribe on events sent by client associated with that socket instance.
Here is the different parts of your program explained:
io.on('connection', function(socket){ // Waiting for new clients to connect, then return a socket instance
// msg can be any javascript object like a string or array ect.
socket.on('chat message', function(msg){ // Subscribe on event 'chat message' will be called when client do io.emit
io.emit('chat message', msg); // Server send to clients
});
});

Type of the variable msg is not exactly String but more like whatever emitted in the 'chat message' event. You don't have to emit only strings, you can emit objects too. In the context of the example, yes. It is from the client side.
The variable socket though, socket is the connection between client and the server. If the server receives a 'chat message' event from that connection, or rather 'socket', it emits a 'chat message' event on all the sockets that it has. The content of the 'chat message' event that server emits to all sockets that are connected to it is the same as the content of the 'chat message' event that client, which sent the chat message, emitted to the server in the first place.

Related

Socket.IO Can't emit message from serer to client

I have a connection with the server and client and have the server listening for a player to be made in the lobby. The server receives the player name and updates the player, however, when emitting the player back to the client I am having issues.
Simply, the pseudo-structure of our implementation follows as such...
Server
io.on('connection', function(socket){ ....
socket.emit('ack', {....
socket.on('createPlayer', function(data){
.... (update newPlayer object) .....
socket.emit('newPlayer', {
playerName: newPlayer.name
[...]
Client
let socket = io();
socket.on('ack', function(data) {
console.log('ack', data)
}
socket.on('newPlayer', function(data) {
console.log('newPlayer', data)
When a connection is made by the client's browser to the server, the 'ack' message is sent and received and logged to the client's console. But, When the client makes a new player and the 'createPlayer' socket.on is hit it tries to emit the new player back to the client but is never received.
Any suggestions as to why the client would never receive the sent message?
You should use this for sending message to all connected clients:
io.emit('event_name', msg);
Also you should use this for all clients except new clients:
socket.broadcast.emit('event_name', msg);
This function is for sending message to new client that sent message at that time:
socket.emit('event_name', msg)
You can send specified client using this method:
io.to(socketId).emit('event_name', data)

How to Callback socket.io client using sails.sockets.js onconnect event?

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

socket io: how to pass paramter to disconnet socket event?

I am using socket io for building a chat app.
when "user x" is disconneting from the chat I want to print to the console log: "bye user x".
for that to happen I need to pass as a paramater the user_name to the disconnect event.
problem is that I don't know how to pass data to the disconnect event:
socket.on('disconnect', function(){...})
it is being called automaticly when user disconnected.
I ned to have something like
socket.on('disconnect', function(user_name){
console.log('bye '+user_name);
})
but if that is possible (is it?) then how can I pass this parameter in the client side (my case, angular)?
my complete socket io server.js code is below.
io.on('connection', function(socket){
io.emit('chat_message', "welcome");
socket.on('room', function(room) {
socket.join(room);
});
socket.on('chat_message', function(data){
socket.broadcast.to(data.room).emit('chat_message',data.msg);
});
socket.on('info_message', function(data){
socket.broadcast.to(data.room).emit('info_message',data.msg);
});
socket.on('disconnect', function(){
console.log('bye '+socket.id);
io.emit('chat message', "Bye");
});
});
You can't pass data to the disconnect event. You can however attach your own properties to the socket object at some earlier point or you can keep your own map of sockets with additional information.
You just need to make sure that the server knows the user name for each socket (I can't tell from your question if the user name is a client-side or server-side piece of data). Then, you can just attach it to the socket object as a property. After doing that, when you then get the disconnect event, you can just look at that property on the socket that is disconnecting.
So, wherever the username info comes from, you set that property on the socket object at the time the server knows what it as and then you can do this for the disconnect:
socket.on('disconnect', function(){
console.log('bye ' + socket.user_name);
});
Or, if the user name is in a cookie, you can fetch that cookie value at any time by parsing socket.handshake.headers.cookie.

io.emit vs socket.emit

I'm new to socket.io and have run in to something that seems pretty weird. I don't actually know the difference between socket.emit and io.emit but I can't find an explanation anywhere.
io.on('connection', function(socket){
io.emit('connected') // <<<< HERE >> socket.emit('connected');
socket.on('disconnect', function(){
io.emit('disconnect')
});
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
server.listen(3000);
That's my server stuff however when I change the io to socket that message only gets displayed when the user who is connecting connects. io.emit sends the message to all users.
Maybe it's supposed to be like that or maybe its just some horrible hack? Let me know if you need the client side HTML.
Here's a supplementary documentation for reference :
socket.emit('message', "this is a test"); //sending to sender-client only
socket.broadcast.emit('message', "this is a test"); //sending to all clients except sender
socket.broadcast.to('game').emit('message', 'nice game'); //sending to all clients in 'game' room(channel) except sender
socket.to('game').emit('message', 'enjoy the game'); //sending to sender client, only if they are in 'game' room(channel)
socket.broadcast.to(socketid).emit('message', 'for your eyes only'); //sending to individual socketid
io.emit('message', "this is a test"); //sending to all clients, include sender
io.in('game').emit('message', 'cool game'); //sending to all clients in 'game' room(channel), include sender
io.of('myNamespace').emit('message', 'gg'); //sending to all clients in namespace 'myNamespace', include sender
socket.emit(); //send to all connected clients
socket.broadcast.emit(); //send to all connected clients except the one that sent the message
socket.on(); //event listener, can be called on client to execute on server
io.sockets.socket(); //for emiting to specific clients
io.sockets.emit(); //send to all connected clients (same as socket.emit)
io.sockets.on() ; //initial connection from a client.
Edit: socket.io docs also contain similar cheatsheet.
The io variable represents the group of sockets. The code you have starts on line one with providing a function in the second parameter that gives you a socket variable every time a new connection is made. The socket variable is only for communicating with each individual connection. You may not see it in the code but there will be one socket variable for each connection established
socket.emit will send back message to sender only,
io.emit will
send message to all the client including sender
if you want to send
message to all but not back to sender then socket.broadcast.emit
That's a good question. Here is a sample code that might answer your question.
server.js code:
// Listener for incoming Socket connections
io.on('connection', function(socket){
socket.on('send', function(msg){
console.log('message received/sending: ' + msg);
io.sockets.emit('new', msg);
});
});
index.html code
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" />
<button type="submit">Send</button>
</form>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
var socket = io();
function send(msg) {
console.log("emitting: " + msg);
socket.emit('send', { "message": msg });
}
socket.on('new', function (msg) {
console.log("msg " + msg.message);
$('#messages').append($('<li>').text(msg.message));
});
$(function () {
$('form').submit(function (e) {
e.preventDefault();
send($('#m').val());
$('#m').val('');
return false;
});
});
</script>
</body>
In index.html socket.emit('send', { "message": msg }); this line of code actually sends/emits message to server which is waiting to listen on socket.on('send', function(msg){ this line of code in server.js.
Now io.sockets.emit('new', msg); this line from server.js emits that message to all its sockets and is displayed to users using its listener in index.html that is socket.on('new', function (msg) {.
Simply said Each socket emits its msg to a server(io is an instance of server) and server, in turn, emits it to all connected sockets. That is how msg sent by any user is displayed to all users. I hope it helps!

Socketio send message to specific client in namespace

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.

Categories