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!
Related
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)
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'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.
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.
Here is my app.js file
io.on('connection', function(socket){
socket.on('ujwal', function (data) {
socket.emit('news', function(){
console.log('testing');
});
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
On ujwal event i am emitting another event to the client
here is my index.html i have included socket lib too
var socket = io('http://localhost:3000');
$('#test').click(function(){
var as = "object";
socket.emit('ujwal',as);
});
socket.on('news', function (a) {
alert('receiving msgs');
});
Now i am opening two windows whenever a user click a test id they are getting but who are not clicking they are not receiving the object in front end why? why code means whenever u get name event ujwal please fire news A and B are connected to server A click the test ujwal is fired and checking by server and again send back news now all the user connected should see the alert ?
This what i know so please make it work so that all user can get alert.
When you use socket.emit(), you're emitting directly to that socket, not all sockets. To emit to all sockets, emit from io
io.on('connection', function(socket){
socket.on('ujwal', function (data) {
//socket.emit('news', function(){
io.emit('news', 'some message');
});
socket.on('disconnect', function(){
console.log('user disconnected');
});