getting an error when trying to use socket.io - javascript

I am currently working with socket.io swift client. Running on Iphone SE. this is the swift code
let socket = SocketIOClient(socketURL: URL(string: "http://example.com:4000")!, config: [.log(true), .forcePolling(true)]);
socket.connect();
socket.on("connect") {data, ack in
print("socket is connected");
socket.emit("getData", ["data": 3]);
}
And on the server:
var express = require('express');
var app = 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');
});
socket.on('getData', function(result){
console.log(result);
});
});
app.listen(4000, function () {
console.log(' on at 4000!');
});
...And on the Xcode console, I get
2016-09-29 16:38:33.871895 proj[3070:1019256] LOG SocketEngine: Handshaking
2016-09-29 16:38:33.872301 proj[3070:1019256] LOG SocketEnginePolling: Doing polling request
2016-09-29 16:38:34.004312 proj[3070:1019256] LOG SocketEnginePolling: Got polling response
2016-09-29 16:38:34.004874 proj[3070:1019283] LOG SocketEngine: Got message: Cannot GET /socket.io/?transport=polling&b64=1
2016-09-29 16:38:34.005283 proj[3070:1019283] ERROR SocketIOClient: Got unknown error from server Cannot GET /socket.io/?transport=polling&b64=1
Which demonstrates a connection is made and the server is successfully found, but something else is wrong.
Would appreciate any help.

(Sidenote: If you don't need support for old browsers (or any browsers for that matter, since your client is a native mobile app) then you may consider using WebSocket which is an open standard. Socket.io is usually used to have a WebSocket-like functionality on browsers that don't support WebSocket. WebSocket on the other hand is an open standard, has a wide support (not only in browsers) and it has a better performance. See this answer for more details.)
Now, since you are already using Socket.io then here is how you can diagnose the problem. I would try to connect from a browser, which is a main way to connect with Socket.io, and see if that works. If it doesn't then it would mean that there's a problem in your server code. If it does then it could mean that there's a problem in your client. That would be the first thing to check. Going from there you can narrow the problem and hopefully fix it.
If you want to have a starting point with some working code using Socket.io, both server-site (Node.js) and client-side (browser vanilla JavaScript), then you can see the examples that I wrote originally for this answer, that are available on GitHub and on npm:
Socket.IO Server
Socket.IO server example using Express.js:
var path = require('path');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
console.error('express connection');
res.sendFile(path.join(__dirname, 'si.html'));
});
io.on('connection', s => {
console.error('socket.io connection');
for (var t = 0; t < 3; t++)
setTimeout(() => s.emit('message', 'message from server'), 1000*t);
});
http.listen(3002, () => console.error('listening on http://localhost:3002/'));
console.error('socket.io example');
Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/si.js
Socket.IO Client
Socket.IO client example using vanilla JavaScript:
var l = document.getElementById('l');
var log = function (m) {
var i = document.createElement('li');
i.innerText = new Date().toISOString()+' '+m;
l.appendChild(i);
}
log('opening socket.io connection');
var s = io();
s.on('connect_error', function (m) { log("error"); });
s.on('connect', function (m) { log("socket.io connection open"); });
s.on('message', function (m) { log(m); });
Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/si.html
You can compare the same code with WebSocket versions:
WebSocket Server
WebSocket server example using Express.js:
var path = require('path');
var app = require('express')();
var ws = require('express-ws')(app);
app.get('/', (req, res) => {
console.error('express connection');
res.sendFile(path.join(__dirname, 'ws.html'));
});
app.ws('/', (s, req) => {
console.error('websocket connection');
for (var t = 0; t < 3; t++)
setTimeout(() => s.send('message from server', ()=>{}), 1000*t);
});
app.listen(3001, () => console.error('listening on http://localhost:3001/'));
console.error('websocket example');
Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.js
WebSocket Client
WebSocket client example using vanilla JavaScript:
var l = document.getElementById('l');
var log = function (m) {
var i = document.createElement('li');
i.innerText = new Date().toISOString()+' '+m;
l.appendChild(i);
}
log('opening websocket connection');
var s = new WebSocket('ws://'+window.location.host+'/');
s.addEventListener('error', function (m) { log("error"); });
s.addEventListener('open', function (m) { log("websocket connection open"); });
s.addEventListener('message', function (m) { log(m.data); });
Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.html
I hope this can help you evaluate whether staying with Socket.io or going with WebSocket is the right decision for you, and will give you some working client-side code to test your backend. The code is released under the MIT license (open source, free software) so feel free to use it in your project.

Related

Express-generator, Socket.io Event issuing multiple times

I have create a node app using express generator. I have integrated socket.io in the application. Since express generator has their own way of creating express server i have followed this procedure to successfully integrate the Socket connection with listening server and made the io available throughout the application via res.io instance.
FILE: bin/www
#!/usr/bin/env node
var app = require('../app').app;
var debug = require('debug')('www:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = require('../app').server;
/app.js
//Express handler
var app = express();
// Socket configuration
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.use(function(req, res, next){
res.io = io;
next();
});
...
module.exports = {app: app, server: server};
But the problem is when i m emitting an event as shown below. My client is reading the data multiple times.
routes/index.js
var clients = 0;
var nsp = res.io.of('/default-namespace');
nsp.on('connection', function (socket) {
clients++;
console.log(clients + ' clients connected!');
socket.on('disconnect', (reason) => {
clients--;
console.log(clients + ' clients connected!');
});
nsp.emit("socketToMe", "New User connected. Current clients:"+ clients);
});
My listener has the following code:
home.pug
var socket = io('/default-namespace');
socket.on('socketToMe', function (data) {
$('#data-div').append($('<li>').text(data));
});
Whenever i refresh the browser in another instance like incoginito my main browser is showing multiple events for the data. Like this
New User connected. Current clients:1
New User connected. Current clients:2
New User connected. Current clients:1
New User connected. Current clients:2
New User connected. Current clients:1
New User connected. Current clients:1
Not sure what is wrong. Can anyone help me on this?
Nodejs is event driven.The res object is not a global variable.
Express middleware runs for every request.
var clients = 0;
var nsp = res.io.of('/default-namespace');
nsp.on('connection', function (socket) {
clients++;
console.log(clients + ' clients connected!');
socket.on('disconnect', (reason) => {
clients--;
console.log(clients + ' clients connected!');
});
nsp.emit("socketToMe", "New User connected. Current
clients:"+clients);
});
Let me explain what happens above.A user requests and req handler is fired and you access the res object and you listen for events.
So for each request, you are listening for socket 'connection' event.That means you are setting multiple event listeners with the same name.Every time you make a request you set a new listener.
You are supposed to set only a single 'connection' listener.
This explains emitting the same event multiple times.
app.use(function(req, res, next){
res.io = io;
next();
});
Instead of using the above middleware function,listen directly on io instance

client code in node js

I am new to Nodejs and am trying to set up a server client connection using sockets. Below is my code. Server is working OK but client is not connecting.
Please can anyone help me figure out the mistake.
Much Thanks
jessi
Server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
io.on('data', function(data) {
console.log('DATA from client is: ' + data);
// Close the client socket completely
});
server.listen(4200);
console.log('Monitoring server listening on port 4200');
Client.js
var HOST = '127.0.0.1';
var PORT = 4200;
var express = require('express');
var app = express();
var client = require('http').createServer(app);
var io = require('socket.io')(client);
client.connect(PORT, HOST, function()
{
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected,
// the server will receive it as message from the client
io.write('I am Chuck Norris!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
For the client you use the socket.io-client package instead. The client side doesn't require the use of the Express portion since you're not recreating a web server on the client. If you look at your current code you're essentially recreating the Socket server which isn't what you want to do.
All that is necessary is to create a new Socket.io client and register your various event handlers.
var socket = require('socket.io-client')('localhost:4200');
socket.on('data', function(data) {
// handle incoming data
console.log(data);
});

How can I have faye-websockets code running in the browser?

I'm new with node.js/express and all and I want to be able to notify any clients in browser about a new message received from some algorithm in the back-end. The publisher algorithm connect to the websocket and writes the message.
As far as I've looked there were examples which recommended websockets but I haven't been able to run that code in browser only in console.
Example client code:
var WebSocket = require('faye-websocket');
var ws = new WebSocket.Client('ws://localhost:1234');
var http = require('http');
var port = process.env.PORT || 1235;
var server = http.createServer()
.listen(port);
// receive a message from the server
ws.on('message', function(event) {
alert(JSON.parse(event.data));
});
Thank you
Found the answer after some trial/error iterations.
The algorithm now does a POST to an URL which in turn triggers a write to sockets for all connected clients via socket.io.
Client code:
var socket = io('http://localhost:7777');
socket.on('message', function (msg) {
document.body.insertAdjacentHTML( 'beforeend', '<div id="myID">'+msg+'</div>' );
});
And on the server, when client connects I retain it's socket into an array so I can write to each one:
Server code:
io.on('connection', function(socket){
console.log('a user connected: '+socket.id);
var id = clientCount++;
clientSockets[id] = socket;
socket.on('disconnect', function(){
console.log('user disconnected');
delete clientSockets[id];
socket = null
});
});
app.post('/alerts', function(req, res) {
req.accepts(['json', 'application']);
console.log("Algo did a POST on /alerts!");
// send the message to all clients
//console.log(req.body);
for(var i in clientSockets) {
clientSockets[i].send(JSON.stringify(req.body));
}
res.send(200);
});
In conclusion, I'm not using faye-websockets but instead socket.io

socket.io connection not heppening

This is first time, I am using socket.io.I stuck at initial stage itself.sorry it's may be simple question.
server side code :
Inside my server.js I written the following code.
var express = require('express')
,io=require('socket.io')
,http = require('http')
var app = express();
server = http.createServer(app);
io = io.listen(server,{ log: false });
Now I trying to make connection inside server.js file,like in the following way.
io.sockets.on('connection', function (socket) {
console.log("This is testing");
io.to(socket.id).emit('notification', 'for your eyes only');
});
client side code :
var socket = io.connect("http://localhost");
socket.on('connect', function () {
console.log("connect")
});
socket.on('notification', function (data) {
console.log(data);
});
I open application in browser, as per my code it suppose to console connect statement but it's not happening.
my server is running on port no :80Where am I did wrong, can anyone help me.
Thanks.
Here is the working code for me in express it may help you.
var express = require('express')
, app = express()
, server = require('http').Server(app)
, io = require('socket.io')(server)
var defaultPort = 6001 ;
server.listen(defaultPort, function() {
console.log('Server Started');
});
io.sockets.once('connection', function(socket) {
return io.sockets.emit('new-data', {
channel: 'stdout',
value: "Your Data Goes Here"
});
socket.on('disconnect', function(){
});
});
On Client Side
<script>
$(function() {
var socket = io.connect('http://localhost'); //if you are trying on server put server url if you are working on local then use localhost
socket.on('new-data', function(data) {
$('#YouDivid').html(data.value);
});
});
</script>

socket.io reconnect socket.socket.connect doesn't work

sorry for posting this issue again, but most of the posts related don't answer my question.
i'm having issues to use multiple connections with the socket.io
i don't get the "socket.socket.connect" method to work, yet i get feedbacks from the first connection.
Here's my structure:
var iosocket = null;
var firstconnection = true;
var ip = "http://xxx.xxx.xxx"
var ipPort = 8081
function callSocket() {
iosocket = null;
iosocket = io.connect(ip,{port:ipPort,rememberTransport:true, timeout:1500});
if (firstconnection) {
firstconnection= false;
iosocket = io.connect(ip,{port:ipPort,rememberTransport:true, timeout:1500});
iosocket.on('connect', function () {console.log("hello socket");});
iosocket.on('message', function(message) {});//end of message io.socket
iosocket.on('disconnect', function () {console.log("disconnected");});
} else {
if (iosocket.connected === true) {
console.log("heyhey still connected");
iosocket.disconnect();
}
iosocket.socket.connect(ip,{port:ipPort,rememberTransport:true,timeout:1500});
}
};
it simply doesn't get any feedback from the second connection
i simply solved that IE8 bug by adding
<!DOCTYPE html>
at the top of the html
I think I know why this isn't working. For server-side code, this doesn't seem correct for socket.io. The connect method is used for clients and not servers. I think you are trying to make the server listen on a port. In that case, you should do:
var socket = require('socket.io');
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = socket.listen(server);
io.on('connection', function (client) {
client.on('someEvent', function(someVariables){
//Do something with someVariables when the client emits 'someEvent'
io.emit('anEventToClients', someData);
});
client.on('anotherEvent', function(someMoreVariables){
//Do more things with someMoreVariables when the client emits 'anotherEvent'
io.emit('anotherEventToClients', someMoreData);
});
});
server.listen(8000);

Categories

Resources