socketio javascript confusion - javascript

I have seen a few examples of socket.io.js.
On the client side the call to create the connection is always
var socket = io.connect();
However, this is just creating a point to a function.
How is this enough without another line calling socket?
Is this not just a variable declaration?

Calling io.connect() on the client without any arguments returns the socket object representing the connection. Since it's on the client you don't have to do anything like...
io.on('connection', function (socket) {
// do stuff with socket
});
...like you do on the server. The server expects many clients to connect to it, but the client only ever connects to one server. On the client
var socket = io.connect();
...is plenty. You can also pass options to io.connect(), such as a different URL to connect to.
var socket = io.connect('/my/socket/server/endpoint');

Related

How do I use a single connection with socket.io

I am making a real time multiplayer game with socket.io and node.js, I have a html file that runs a public script to connect to the server and run commands, as well as defining the library I need with
<script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
I have a connect and disconnect function in thew public js file that has these functions:
// send join request
function joinlobby(room) {
socket.emit("userJoined", room);
}
// emit when a player leaves
function leavelobby(room) {
socket.emit("userLeft", room);
}
and whenever I create a new socket within the function with something like
// emit when a player leaves
function leavelobby(room) {
let socket = io();
socket.emit("userLeft", room);
}
it will run correctly, however with both having a separate connection it causes issues. I was trying to have them use the same connection by having let socket = io(); placed above the functions to use the same socket, however when the program hits that line it stops running the file without throwing an error
How could I use a single connection to the server, and/or why is the program disconnecting when I define the socket outside a function?
Edit for clarity:
The issue isn't wanting a single connection for every client, but rather each client has multiple connections whenever I define the socket in each respective function. I am aiming at only having 1 connection for each client but the line throws an error
I'm sorry for the ambiguity, I'm new to asking questions on here
When you create a connection to the socket server each client will have his own connection, if you want to send a single message to multiple clients you should use rooms. It is pretty easy to use:
io.on("connection", socket => {
socket.join("room1");
});
If boot clients are connected to the same room you will be able to send a message to that room.
io.to("room1").emit("Hello every body");
More info here: https://socket.io/docs/v3/rooms/

Socket IO keeps disconnecting and reconnecting

I'm very very new to sockets and socket.io, so I apologize if this is an obvious question. I'm using the C# client for Socket.IO and have a local javascript server running. Here is my app.js:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket) {
console.log('A user connected');
socket.on('test', function () {
console.log('Test run'); });
socket.on('disconnect', function () {
console.log('A user disconnected'); });
});
http.listen(3000, function() {
console.log('listening on localhost:3000'); });
In my main C# class (it is a Windows Forms application) the only line of code I have relating to the sockets at all is the instance variable private Socket socket = IO.Socket("http://localhost:3000/");. Yet for some reason, the server repeatedly receives the connect and disconnect events. Here is a screenshot of my console:
screenshot
This all happens automatically, as soon as I run my C# program, without any interaction, and stops as soon as I close it. Any ideas as to why it keeps connecting/disconnecting?
EDIT: For whatever reason the problem seems to go away when I remove Newtonsoft.json from the project. However, without it I cannot use the Emit function as well as others. Is there a workaround to this?
To anyone encountering this issue, check if client & server speak the same protocol version.
On a high-level, this is likely to be caused by protocol version mismatch between server and client. I've had the same issue in JS app. Turned out I was using some older version of socket.io on the client and the latest on the server. In the repository you provided we can find:
// EngineIoClientDotNet/Src/EngineIoClientDotNet.mono/Parser/Parser.cs
public static readonly int Protocol = 3;
So this (now deprecated) client is using Engine.IO protocol v3. You didn't provide info which socket.io version you were using on the server, but it simply might've been using different revision on Engine.IO protocol.
As a side note, speaking more low-level: I guess that the client might be able to connect, but it does not respond to server's first ping command in a proper way (or the other way around). Therefore the connection is immediately dropped. Socket.IO has a history of breaking changes in how ping-pong mechanism is implemented, and this might be the underlying root cause.

How to connect the backend to server the frontend to make realtime chatting using socket.io with different users

I'm using Mongoose to store the chat between different registered users, at the current implementation they can retrieve chat logs if they refresh the page! which is not identical to be a real-time solution.
How to use socket.io() to act as sender/receiver for many users.
I followed
https://socket.io/get-started/chat/
and
https://medium.freecodecamp.org/simple-chat-application-in-node-js-using-express-mongoose-and-socket-io-ee62d94f5804
But both, they assume the same port for the same user.
It is always a better idea to refer to the official API documentation.
https://socket.io/docs/client-api/
In your case, you need to create a separate socket for a separate private chat
//Join PrivateRoom - client
var socket = io.connect('http://localhost');
socket.emit('joinprivate', {email: user1#example.com});
//Server
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.on('joinprivate', function (data) {
socket.join(data.email); // We are using room of socket io
});
});
More examples:
How to send a message to a particular client with socket.io

How does socket.io on the client listen to events emitted from server?

I have the following code on my client side:
btn.addEventListener('click', function(){
socket.emit('chat',{
message: message.value,
handle: handle.value
});
});
So I think I understand the above. When a click event happens, run the callback function. Inside the callback function, have socket emit this "chat" event to the server. Along with the event socket emits, pass the JSON data.
Now on the server side we have this:
var io = socket(server);
io.on('connection', function(socket){
socket.on('chat', function(data){
io.emit('chat', data);
});
});
I think I understand this as well. Bind the socket to this server. Then listen to the connection event. When that event is invoked, socket.io (will magically?) pass a socket object to our function. We then listen to all of our sockets for a chat. As defined on the client side, take the data emited from the chat and emit it back to all of our sockets.
socket.on('chat', function(data){
// do cool stuff
})
Again in the above example, we have the client listening to the event on the server side.
My question is, how does the event get "passed" to the client side? Is this some sort of native Javascript functionality? I would like to know more of what happens on the backend.
The event gets passed to the server through websockets. Its a tcp connection from the browser to the server. The connection is full duplex meaning the server can send real time data to the client and vise versa.
In your frontend code you should have something that looks similar to
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
This code asks the server for a tcp connection using web sockets. Once the browser is connected to the server through websockets, socket.io can send events to the send through the connection.
The socket that is passed in the connection event is just a reference to whatever socket gets created when the frontend connects. The socket gets a unique id and with this reference you can communicate in real time to the web browser client.
If you want a deep dive into web sockets, I'd recommend reading this
https://www.rfc-editor.org/rfc/rfc6455

unix sockets on nodeJs

Quick and basic nodeJs question,
I'm working with unix socket for inter-server communication between c++ application and my NodeJs server,
I've wrote my nodeJs server like so:
var net = require('net');
var unixSocketServer = net.createConnection('/tmp/unixSocket');
unixSocketServer.on('connect',function(){
console.log('unix server socket connected on /tmp/unixSocket');
...
});
However I'm getting connection refuse error.
I can understand that the c++ application haven't opened/connected to the socket yet.
My questions are
why does it matter? shouldn't the nodeJs server wait until 'connect' event emitted?
Am I using nodeJs currently? am I missing something?
Ok, so there's some misunderstanding here. Let's start from what a 'unix socket' really is. I think you're thinking it's just a file-like item that acts like a server on its own through the OS/filesystem. That's not quite correct. While it is indeed bound through the filesystem, it isn't really a traditional file. Instead, it's just like an TCP/IP socket, except instead of binding an IP and port, a filepath is bound.
The key point there is that it's just a bound socket with a different type of address (and some extra capabilities, but that's outside the scope here). So that means that something has to bind the socket! In this case, we need a server, just like we would if we were communicating over a 'normal' port. If there isn't a server bound to the path, you get an error, just like you would when connecting to a port with no listener.
To create a server on a unix domain socket in node, it's pretty simple:
'use strict';
const net = require('net');
const unixSocketServer = net.createServer();
unixSocketServer.listen('/tmp/unixSocket', () => {
console.log('now listening');
});
unixSocketServer.on('connection', (s) => {
console.log('got connection!');
s.write('hello world');
s.end();
});
Note that there is one other difference between 'normal' sockets and unix domain sockets: After a server is done with the unix domain socket, it is not automatically destroyed. You must instead unlink /tmp/unixSocket in order to reuse that 'address'/path

Categories