Is there any way to disconnect a client connection of socket.io in the server.js? - socket.io

I know the client part may use disconnect method to disconnect a client connection.
but I can't find any way to disconnect from the server part.
socket.on('connection', function(client) {
client.on('message', function(message) {
var sessionId = message.disId;
socket.disconnect(sessionId);//to disconnect another client
});
});

The server can kick a particular client by using either of these methods:
client._onDisconnect();
(or)
socket.clients[kickedUserSocketId].onDisconnect();
Credit to SeanColombo on GitHub

Related

Socket.io don't emit after disconnect event

I want to send data from the server to the client after a disconnect socket.io event occurs.
Server :
const clients = {};
io.on('connection', socket => {
clients[socket.id] = socket;
console.log('connect : ' + socket.id);
socket.emit('socket-connect', 'connected');
socket.on('disconnect', () => {
socket.emit('socket-disconnect', 'disconnected');
delete clients[socket.id];
console.log('disconnect : ' + socket.id);
});
});
Client :
const socket = openSocket('localhost');
socket.on('socket-connect', data => {
console.log(data);
});
socket.on('socket-disconnect', data => {
console.log(data);
});
If socket connected, the server send a connect message to client and it works, but it does not send interrupted messages to the client if the disconnection occurs.
console.log('disconnect : ' + socket.id); on server showing disconnect with the socket.id.
I'm using socket.io v2.0.4 both on server and client.
How can I send data from the server if a socket disconnect event occurs?
Event: disconnect is fired upon disconnection. This simply means, for some reason, there is no connection between the client and the server.
So in this situation, you cannot send data to the client as the client is not connected. Disconnection may happen if the client's network is not available(read Internet failure) or the client environment(ex: browser) crashed or the user closed the tab.

Socket.emit() outside socket.on()

Do we always have to use socket.emit() inside a socket.on() like that:
io.sockets.on('connection', function (socket) {
console.log('User connected !');
retrieveDictionnary((dictionnary) =>{
socket.emit('dictionnarySend', dictionnary);
}
}
I want to create on my client side a function which ask information to the server when I click on a button:
translateServer(parameter, control){
this.socket.emit('translate', [parameter,control]);
}
But it seems that it's not working, the server never receive this message.
Thank you !
The pattern you are using above is the recommended way of interacting with a socket (ie acquiring a socket instance when the 'connection' event fires, and then calling emit() from that socket instance, etc).
If I understand your client-side requirements correctly, you are wanting to send data to the server via web sockets - are you sure the socket that you have established a web socket connection between the client and server?
For instance, if you add the following to your client-side code, you should see a success message in your console:
const socket = io.connect('YOUR SERVER ADDRESS');
socket.on('connect', () => {
console.log('connected to server!');
// [UPDATE]
// This assumes you have a <button> element on your page. When
// clicked, a message will be sent to the server via sockets
document.querySelector('button').addEventListener('click', (event) => {
// Prevent button click reloading page
event.preventDefault();
// Send message to server via socket
socket.emit('MESSAGE_ID', 'test message from client' + new Date());
});
});
Update
This shows your original server code, expanded with the detail needed to receive and print data sent from client via sockets:
io.sockets.on('connection', function (socket) {
console.log('User connected !');
// Register a server handler for any messages from client on MESSAGE_ID channel
socket.on('MESSAGE_ID', (message) => {
// Print the message received from client in console
console.log('message from client', message);
})
retrieveDictionnary((dictionnary) =>{
socket.emit('dictionnarySend', dictionnary);
}
}

socket.io connection event never fire

server
var io = require('socket.io'),
UUID = require('node-uuid'),
gameport = 3000;
var db = {
waiting_clients: []
};
var logic = {
};
var sio = io.listen(gameport);
sio.sockets.on('connection', function(socket){
var client = {
id: UUID()
};
socket.emit('news', client);
console.log(client.id);
db.waiting_clients.push(client);
});
test client:
var net = require('net');
var client = net.connect({port: 3000},
function(e) { //'connect' listener
console.log('client connected');
client.end();
});
in test client console, it show "client connected". But there are no output in server console
You must use a socket.io client to connect to a socket.io server. Your code shows that you are trying to make a generic TCP connection to a socket.io server. That will not work. The lowest level connection will be established, but then the initial protocol handshake will fail and the socket.io server will drop the connection and you will never get the connection event.
Socket.io has its own connection scheme built on top of webSocket which is built on top of HTTP which is built on top of TCP.
So, to connect to a socket.io server, you must use a socket.io client that runs both the socket.io and webSocket protocol, not a plain TCP socket.

Connect to a sails.js instance via websockets

Is it possible to connect any external application to my sails.js application via WebSockets?
I can use the underlying socket.io embedded in sails.js to talk between the client and server, that's not a problem.
But, I would like to connect another, separate, application to the sails.js server via websockets, and have those two communicate with each other that way, and I am wondering if this is possible?
If so, how can we do this?
Thanks.
Based on SailsJS documentation, we have access to the io object of socket.io, via sails.io.
From that, I just adjusted boostrap.js:
module.exports.bootstrap = function (cb) {
sails.io.on('connection', function (socket) {
socket.on('helloFromClient', function (data) {
console.log('helloFromClient', data);
socket.emit('helloFromServer', {server: 'says hello'});
});
});
cb();
};
Then, in my other nodejs application, which could also be another SailsJS application and I will test that later on, I simply connected and sent a message:
var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000');
socket.emit('helloFromClient', {client: 'says hello'});
socket.on('helloFromServer', function (data) {
console.log('helloFromServer', data);
});
And here are the outputs.
In SailsJS I see:
helloFromClient { client: 'says hello' }
In my client nodejs app I see:
helloFromServer { server: 'says hello' }
So, it seems to be working just fine.

Is it possible to use socket.io server with pure html5 websockets?

I want to use sockets in my web app. I don't want to use socket.io library on client-side. It's OK for server-side though. Can I do this?
Now with socket.io on server and pure websocket on client I have destroying non-socket.io upgrade error. I've googled that it means that I have to use socket.io-client library on client-side. Is there any way to avoid that? I don't want client to be tight with this library and use pure html5 websocket instead.
If it's not possible what should I use for server to connect with pure html5 websockets?
If someone is curious here is my server code (coffeescript file)
# Require HTTP module (to start server) and Socket.IO
http = require 'http'
io = require 'socket.io'
# Start the server at port 8080
server = http.createServer (req, res) ->
# Send HTML headers and message
res.writeHead 200, { 'Content-Type': 'text/html' }
res.end "<h1>Hello from server!</h1>"
server.listen 8080
# Create a Socket.IO instance, passing it our server
socket = io.listen server
# Add a connect listener
socket.on 'connection', (client) ->
# Create periodical which ends a message to the client every 5 seconds
interval = setInterval ->
client.send "This is a message from the server! #{new Date().getTime()}"
, 5000
# Success! Now listen to messages to be received
client.on 'message', (event) ->
console.log 'Received message from client!', event
client.on 'disconnect', ->
clearInterval interval
console.log 'Server has disconnected'
And here is a client-side
<script>
// Create a socket instance
socket = new WebSocket('ws://myservername:8080');
// Open the socket
socket.onopen = function (event) {
console.log('Socket opened on client side', event);
// Listen for messages
socket.onmessage = function (event) {
console.log('Client received a message', event);
};
// Listen for socket closes
socket.onclose = function (event) {
console.log('Client notified socket has closed', event);
};
};
</script>
I've found this library, seems OK for my needs https://npmjs.org/package/ws

Resources