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.
Related
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});
});
},
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.
var io = require('socket.io').listen(server1);
io.on('connection', function(io){
socket_call_data = function(some,data){
io.emit("new_peer_data", result);
}
io.on('event', function(data){
//doing stuff
socket_call_data(some,data);
});
});
This is my current code and the problem is that io.emit (in the function socket_call_data) only seems to emit to the user who connected. So, after doing some reading, I used io.broadcast.emit. This worked great, however it does not include the user who connected - who I do also want to be sent the data. So, finally i came to find out about io.sockets.emit which supposedly sends it to all clients. But instead, i get the error:
Missing error handler on `socket`.
TypeError: Cannot call method 'emit' of undefined
at socket_call_data (/var/www/html/live_nodejs/handle.js:47:20)
So io.sockets.emit is not defined...
What am I getting wrong?
Thanks
It looks like you're overwriting your io variable with a single socket when the user connects. Change the io arg on your connection event to socket instead:
var io = require('socket.io').listen(server1);
io.on('connection', function(socket){
socket_call_data = function(some,data){
io.emit("new_peer_data", result);
}
socket.on('event', function(data){
//doing stuff
socket_call_data(some,data);
});
});
Then io.emit() should emit to all sockets.
What is happening is that you are passing io in the function
io.on('connection', function(io){
//Your Code here
});
so, the Global io and the io that you are passing inside the function are becoming ambiguous. All you need to do is, change the io that you are passing inside the function to some other variable like socket or something.
io.on('connection', function(socket){
//Your code here
socket.emit("some event specific to this particular socket");
io.sockets.emit("This event will be broadcasted to everyone connected");
});
This should help you out.
I want to know which client sent an event when it arrives on the server. For example:
var socket = require(socket.io')(port);
socket.on("ask question", function(data){
var socketid = // ?
//respond to sender
socket.sockets.connected[socketid].emit("Here's the answer");
});
How can I get the socket ID of the event sender?
Your server-side logic is a bit off. The client connects and that's where the client socket is revealed and that's where you listen to events from a particular client. Usually, it would look like this:
var io = require("socket.io")(port);
io.on('connection', function (socket) {
socket.on('ask question', function (data) {
// the client socket that sent this message is in the
// socket variable here from the parent scope
socket.emit("Here's the answer");
});
});
This is shown in the socket.io docs here.
Is it possible for client to send a socket data when it gets
disconnected (user closes the browser, or tab)?
Because, I found that default bind on disconnect doesn't take any input data.
//on server side
socket.on('disconnect',function(){
//in other binds, it takes 'data' as an input but this does not
});
I tried to resolve this problem by using the jQuery's unload method
like below
//on client side
$(window).unload(function(){
socket.emit('depart','I am leaving');
});
However, it does not seem to emit at all on unload. (maybe socket gets out of scope on unload?)
Is there a way to send data through websocket to the server when client disconnects?
Secondly, Is there any way that I can store a string data in socket? For instance,
socket.userName = userNameVar;
--update--
Here is how I set up environment on the serverside
io.sockets.on('connection',function(socket){
socket.on('depart',function(data){
console.log(data);
console.log("user left");
});
socket.on('disconnect',function(){
console.log("user disconnected");
});
});
and following code is in the client side.
var socket = io.connect(hostVar);
$(window).unload(function(){
socket.emit('depart','I am leaving');
});
The reason you cannot send data on disconnect is because you are disconnected. What you are asking is somewhat akin to saying "Can i still talk to the person on the phone after they've hung up on me?"
If you want to emit the 'depart' event, then you still have to capture it inside your 'connect' handler on server side:
As in:
io.socket.on('connection', function(socket) {
socket.on('depart', function(msg) {
// you should get depart message here
});
})
Your depart event will come BEFORE the connection is terminated. disconnect is only raised by server upon a successful disconnection and therefore it cannot receive any messages.
Give it a try and tell me if this works :)
Use this instead
$(window).on('beforeunload',()=>{
socket.emit('page_unload');
});
and on server side
io.socket.on('connection', function(socket) {
socket.on('page_unload', function(msg) {
// client has reloaded page or closed page
});
})