I'm learning Socket.io with node js ,express
In this code :
io.sockets.on('connection', function (socket) {
console.log('Log !');
});
What it's use the parameters socket in this function ?
Thanks.
The socket parameter gives you information about the connected client, such as the unique socket.id which will help you send events to that specific socket, you can see in what rooms the socket is in, you can get information about the browser and more, you can inspect it with console.log(socket) and see a lot of information that you can use
Related
I am trying to send data to all clients just to test how socket.io works.
I can't seem to get any data back from the server, no matter how I try.
The event is fired, so the data gets to the server side, but it doesn't arrive to the clients.
On the server side, I do this:
io.on('connection', (socket) => {
socket.on('chatMessage', data => {
console.log(data);
io.emit(data);
});
});
The console.log() here works, so its fine until that line.
On the client side I tried to simplify things to see the result like this:
const socket = io.connect('http://localhost:5000');
socket.on('connect', () => {
socket.emit('chatMessage', {a:"fsdfsdfsd"});
});
socket.on('chatMessage', data =>{
console.log(data);
});
The socket.emit() fires, but it doesn't arrive anywhere.
I have never used socket.io before, but I read the docs and it said io.emit() sends the data to all connected clients.
Just in case, I tried with multiple clients connected, but it still doesn't work.
First thing I would recommend is to check if the client is really connecting to the server socket by adding a console.log() inside your on connection block in the server side.
Also, your io.emit(data); in the server side won't work since the first parameter of the emit function should be the event name.
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:)
How do I store session specific info in Socket.io?
var client={}; //is this static across all sockets (or connected clients) that are connected?
io.on('connection', function(socket){
client.connectiontime=Date.now();
});
//on another io.on('connection') for the same connected client
io.on('connection', function(socket){
store(client.connectiontime);
}
How do I use the client variable only for the operations related to the currently connected client if it is considered static?
First, each socket is given a name that can be used to refer to it, but that changes each time the same client connects so this would not be useful if it is supposed to remain after the client leaves. If your goal is to store the connection time somewhere (a database?) then you would have to get a unique identifier from the client that could be used to find them again similar to a login. You would then pass the date object into the function that handles storing that time.
You should note though, that 'connection' is only called the first time the socket connects. A connection is not the event you normally would be using for when a client does something unless they disconnects between each access of the server program.
If you are sure you want to just use the Client object, you would likely have to create a client array and use the socket id as a key to access the object later. You would then have something like
array[socket.id].connectiontime = Date.now()
var client={}; //is this static across all sockets (or connected clients) that are connected?
var clients = [];
io.on('connection', function(socket){
clients[] = {
id : socket.id
connectiontime : Date.now()
}
});
//on another io.on('connection') for the same connected client
io.on('connection', function(socket){
// Here you would search for the object by socket.id and then store
store(client.connectiontime);
}
I have the Express code in server JS file:
app.post('/confirm', function (req, res) {
// Here I need to send socket with emit()
});
Below mentioned code I have Socket.io:
io.on('connection', function (client) {
// All methods
});
Problem is that I can not get access to socket in express method app.post() and can not send data by POST action.
How can I use that?
You can emit data to specific connected sockets using the following:
io.to(socket_id).emit('something', {"bar":"foo"});
The "socket_id" variable is, as probably guessed, the socket.id from the connected socket.
You will probably have to store them along with some other identification in an array or object to send data to the correct clients later using express routes.
PS: As your code is
io.on('connection', function (client) {
// All methods
});
you would use client.id to get the socket id.
Why do i see traffic for other rooms in (chrome/network).
Node.js and socket.io 0.9.16
Simplified setup
//sockets-server
socket.on('subscribeToSome', function (data) {
joinToRoom(socket, data);
console.log("joining" + data.room);
});
//client
socket.emit(subscribeToSome, {room: room, data: dataToSubscribe});
socket.on(room, function(data){
console.log(data);
});
//route -server
global.io.sockets.emit("room1", {aa:"ads"}
Everything works but i can see traffic for other rooms in (chrome/network) even doe in not member of it. (data is not visible in the callback only in network/Websockets)
How come? And how do i solve it.
Thanks. //Karl
From what i can see from your code you're not emitting your message to a room but you use an eventname for the message. As shown in the documentation, emit takes a String as the first parameter, giving that message a name which your callbacks are hooked to.
Emitting to a room would look like the following:
global.io.sockets.to("room1").emit("message", {aa:"ads"}
You also need to join your socket into that room for it to receive the respective messages.
See http://socket.io/docs/rooms-and-namespaces/ for more information on that topic.