please look at the code below. It's a simple program in nodeJS.
Question is why disconnect is not printed? (If you uncomment setTimeout, problem is gone)
What is the real question?: Why can't I start socketIO client and server together and close a socket immediately after connection? What is the know-how regarding connections with socketIO?
"use strict";
var Promise = require("bluebird");
var socketio = require("socket.io");
var socketio_client = require("socket.io-client");
var http = require("http");
var port = 7457;
var hostandport = "http://localhost:" + port.toString();
var server = socketio.listen(port);
var client = socketio_client(hostandport);
server.sockets.on("connect", function (socket) {
console.log("connect");
socket.on("disconnect", function () {
console.log("disconnect");
});
//setTimeout(function() {
client.disconnect();
//}, 1000);
});
You have set up your server incorrectly, do this instead:
var server = require('http').createServer(handler);
var io = require('socket.io')(server);
io.on("connect", function (socket) {
console.log("connect");
socket.on("disconnect", function () {
console.log("disconnect");
});
//More importantly, you have done this part wrong,
//the rest of your code may be functional,
//but it does not adhere to what socket.io sets out in its own API
//(http://socket.io/docs/)
socket.disconnect();
});
In Socket.io there is no such thing as connection on server side and/or browser side. There is only one connection. If one of the sides closes it, then it is closed. So you can close it from Server using socket.disconnect()
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('disconnect', function(){
console.log('user disconnected');
});
setTimeout(function() {
socket.disconnect();
}, 1000);
});
Goto http://socket.io/get-started/chat/ for more clarifications.
Related
I have the following example using Node.js for the server that sends data via Socket.io to a Javascript file. All works well locally, but when I uploaded to Heroku, it does not. I have tried a lot of tips I found online, but I am always stuck and can't get it through. At the moment, I don't get errors, but I also can't see the values coming through.
Here is the code I use at the moment:
var express = require('express');
var socket = require('socket.io');
//store the express functions to var app
var app = express();
//Create a server on localhost:3000
var server = app.listen(process.env.PORT || 3000);
//var server = app.listen((process.env.PORT || 3000, function(){
//console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
//});
//host content as static on public
app.use(express.static('public'));
console.log("Node is running on port 3000...");
//assign the server to the socket
var io = socket(server);
//dealing with server events / connection
io.sockets.on('connection', newConnection); //callback
//function that serves the new connection
function newConnection(socket){
console.log('New connection: ' + socket.id);
socket.on('incomingDataToServer', emitFunction);
function emitFunction(data){
//setInterval(() => socket.broadcast.emit('ServerToClient', new Date().toTimeString()), 1000);
let randNum;
setInterval(function(){
//get a random value, and assign it a new variable
randNum = getRandomInt(0, 100);
}, 1000);
socket.broadcast.emit('ServerToClient', randNum);
//following line refers to sending data to all
//io.sockets.emit('mouse', data);
console.log(randNum);
}
}
And the Javascript here:
let socket;
socket = io();
socket.on('ServerToClient', socketEvents);
function socketEvents(data){
incomingData = data;
console.log(data);
}
Any help is appreciated.
Thanks
Write app.use before the app listen
and modify app.listen as below and check heroku logs for console message.
app.use(express.static('public'));
var server = app.listen(port, function() {
console.log('Server running on ' + port + '.');
});
if It still not work let me know.
I have this code working for receiving data from my Arduino but I will like to send data back to my Arduino and get a response on my client page. I added a listening function but I keep getting io.on is not a function when I send data from my client page.
test.js
io.listen(app.listen(3000)).on('connection', function (client) {
// store client into array
clients.push(client);
// on disconnect
client.on('disconnect', function() {
// remove client from array
clients.splice(clients.indexOf(client), 1);
});
// I added this to listen for event from my chart.JS
io.on('connection', function(socket){
socket.on('LED on', function (data) {
console.log(data);
});
socket.on('LED off', function (data) {
console.log(data);
});
});
});
Your value of io is not what it should be.
The usual way of doing things is like this:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
io.on('connect', ...);
But I'm guessing that your value of io is something like this:
var io = require('socket.io');
That's not the same thing. That's the module handle. But, when you do it this way:
var io = require('socket.io')(app);
Then, io is a socket.io instance. You can bind listeners to an instance, not to the module handle.
In every single socket.io server-side example on this doc page, they use one of these forms:
var io = require('socket.io')(app);
var io = require('socket.io')(port);
var io = require('socket.io')(server);
with this:
io.on('connection', ....);
Nowhere do they do:
var io = require('socket.io`);
io.listen(server);
io.on('connection', ....);
That's just the wrong value for io.
Long story, shortened, you need to fix what you assign to io to be consistent with the docs. It's the return value from require('socket.io')(app); that gives you a socket.io instance object that you can then set up event handlers on.
if you are using express
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
let APP_PORT=3000;
server.listen(APP_PORT,()=>{
console.log(`SERVER RUNNING ON PORT : ${APP_PORT}`);
});
io.on('connection', (socket) => {
/* SOCKET - CORE EVENTS */
socket.on('connect', (message) => {
console.log("connected: " + message+"socket_id:"+socket.id);
});
socket.on('disconnect',(data)=>{
console.log('user disconnected:' + socket.id);
});
socket.on('error', function (err){
console.log('received error from client:', socket.id,' Error :',err);
});
});
On server the disconnect event is triggered after connect when the network had
dropped and the client reconnects.
Client code:
var url ='192.168.1.101', port = '80',
socket = io.connect('http://' + url + ':' + port, {
'reconnect': true,
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
timeout: 1000
});
//reconnect event
socket.on('reconnect', function (nr) {
console.log('reconnected, nr: ', nr);
});
//connect event
socket.on('connect', function () {
console.log('connected');
});
//disconnect event
socket.on('disconnect', function () {
console.log('disconnected');
});
Server code:
'use strict';
var fs = require('fs'),
express = require('express'),
app = express(),
io = require('socket.io'),
server = require('http').createServer(app),
compress = require('compression'),
socket;
app.use(compress({level: 9}));
server.listen(port, url);
socket = io.listen(server, {'pingTimeout': 1000, 'pingInterval': 3000});
socket.on('connection', function (client) {
console.log('client connected');
client.on('disconnect', function () {
console.log('client disconnected');
});
});
- Result on server if client reconnects:
> client connected
> client disconnected
Can someone explain to me why this is happening?
The client and server exchange heart beat messages while the connection is active. When the server stops receiving these messages it will declare the client disconnected. The client can also disconnect explicitly.
What you are experiencing though is probably the first case. The client has a retry logic so whenever the connection is dropped it'll try to reconnect. I'm not sure why this is happen, you may want to look at the network tab in your browser's console to see what's happening at the request/response level.
REF:
https://github.com/socketio/socket.io/issues/1910
https://github.com/miguelgrinberg/Flask-SocketIO/issues/116
Are you sure that the client disconnected and client connected texts are from the same socket/connection? Maybe first one is from previous connection and it is just delivered to you a bit later than info about new connection?
Try to generate and add some ID numbers to connections/sockets and output them to console along with info messages.
I'm trying to use socket.io with existing application. My application runs on https://somedomain.com. Its using this code to connect to socket io server:
var socket = io('https://localhost:3456/');
socket.on('connect', function () {
socket.send('hi');
socket.on('message', function (msg) {
// my msg
});
});
My socket.io server has this code to listen to incoming connections:
var io = require('socket.io').listen(3456);
io.sockets.on('connection', function(socket) {
console.log("dupa");
socket.on('message', function() {});
socket.on('disconnect', function() {});
});
dupa is never displayed on server side and in Chrome browser console I receive:
GET https://localhost:3456/socket.io/?EIO=3&transport=polling&t=1412901063154-0 net::ERR_SSL_PROTOCOL_ERROR
How can I get this possibly working?
Change https to http
var socket = io.connect("http://localhost:4000");
Your socket server is not using SSL.
First, add the secure parameter to your client (maybe redundant with the https but SSL+socket.io does weird stuff sometimes):
var socket = io.connect('https://localhost', {secure: true});
Then, you need your socket to be secure too :
var privateKey = fs.readFileSync('YOUR SSL KEY').toString();
var certificate = fs.readFileSync('YOUR SSL CRT').toString();
var ca = fs.readFileSync('YOUR SSL CA').toString();
var io = require('socket.io').listen(3456,{key:privateKey,cert:certificate,ca:ca});
I want to get session id of client in my socket.io client.
here is my socket.io client :
var socket = new io.Socket(config.host, {port: config.port, rememberTransport: false});
// when connected, clear out display
socket.on('connect',function() {
console.log('dummy user connected');
});
socket.on('disconnect',function() {
console.log('disconnected');
});
socket.connect();
return socket;
I want to get session id of this client , how can i get that ?
Have a look at my primer on exactly this topic.
UPDATE:
var sio = require('socket.io'),
app = require('express').createServer();
app.listen(8080);
sio = sio.listen(app);
sio.on('connection', function (client) {
console.log('client connected');
// send the clients id to the client itself.
client.send(client.id);
client.on('disconnect', function () {
console.log('client disconnected');
});
});
On socket.io >=1.0, after the connect event has triggered:
var socket = io('localhost');
var id = socket.io.engine.id
I just had the same problem/question and solved it like this (only client code):
var io = io.connect('localhost');
io.on('connect', function () {
console.log(this.socket.sessionid);
});
* Please Note: as of v0.9 the set and get API has been deprecated *
The following code should only be used for version socket.io < 0.9
See: http://socket.io/docs/migrating-from-0-9/
It can be done through the handshake/authorization mechanism.
var cookie = require('cookie');
io.set('authorization', function (data, accept) {
// check if there's a cookie header
if (data.headers.cookie) {
// if there is, parse the cookie
data.cookie = cookie.parse(data.headers.cookie);
// note that you will need to use the same key to grad the
// session id, as you specified in the Express setup.
data.sessionID = data.cookie['express.sid'];
} else {
// if there isn't, turn down the connection with a message
// and leave the function.
return accept('No cookie transmitted.', false);
}
// accept the incoming connection
accept(null, true);
});
All the attributes, that are assigned to the data object are now accessible through the handshake attribute of the socket.io connection object.
io.sockets.on('connection', function (socket) {
console.log('sessionID ' + socket.handshake.sessionID);
});
On Server side
io.on('connection', socket => {
console.log(socket.id)
})
On Client side
import io from 'socket.io-client';
socket = io.connect('http://localhost:5000');
socket.on('connect', () => {
console.log(socket.id, socket.io.engine.id, socket.json.id)
})
If socket.id, doesn't work, make sure you call it in on('connect') or after the connection.
For some reason
socket.on('connect', function() {
console.log(socket.io.engine.id);
});
did not work for me. However
socket.on('connect', function() {
console.log(io().id);
});
did work for me. Hopefully this is helpful for people who also had issues with getting the id. I use Socket IO >= 1.0, by the way.
Try from your code
socket.socket.sessionid
ie.
var socket = io.connect('http://localhost');
alert(socket.socket.sessionid);
var sendBtn= document.getElementById('btnSend');
sendBtn.onclick= function(){
var userId=document.getElementById('txt1').value;
var userMsg = document.getElementById('txt2').value;
socket.emit('sendto',{username: userId, message: userMsg});
};
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
socket.on('message',function(data){ console.log(data);});
Try this way.
var socket = io.connect('http://...');
console.log(socket.Socket.sessionid);