Using net module in socket.io browser keeps loading - node.js

I want to use the tcp net module in node.js, my clients will be browser and also not browser ( device ).
when I tried to run in the browser the index.html, my browser keeps loading looks like it looping..I dont know what's wrong in my code.
I tried use telnet it works fine, the problem is on the browser i cannot load properly the index.html
//app.js
var net = require('net');
var io = require('socket.io')(net);
var clients = [];
var server = net.createServer(function (socket) {
console.log("New client connected");
clients.push(socket);
});
server.listen(1337, 'localhost', false, function () {
console.log('server bound');
});
io.on('connection',function(socket){
socket.emit('news', { hello: 'world' });
});
here is my client code.
http://pastie.org/10115599

Both the browser and socket.io require an http server, not just a TCP server. You can see the code examples in the socket.io documentation. The first server and client code example on that doc page shows you the basics you need.
In fact, the first step in socket.io connection is an http request that is then "upgraded" to the webSocket protocol. So, the server must be an http server. And socket.io hooks into an http server in order to receive incoming connections.
Here's a code example from the socket.io doc:
Server Code:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
app.listen(80);
io.on('connection', function (socket) {
// incoming socket.io connection established
});
function handler (req, res) {
// process http requests for normal web page serving
}
Client Code:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>

Related

How can I connect a socket to the server?

I'm trying to create a socket in a client.js file to communicate with my server. I followed the official documentation ( https://socket.io/docs/#Using-with-Express ) with no success. Basically when I initialize my socket like this:
var socket = io();
i expect a message from my server (e.g. 'A user has connected') but nothing appear, letting me suppose that the connection never happens.
This is a project made on Glitch. I tried to follow socket.io documentation, simple examples or other questions tips. I both tried the suggested script before instantiate the socket and the cdn one.
//server.js
//dependencies
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
//listening to the port
http.listen(process.env.PORT || 3000, () => {
console.log("Listening on port " + process.env.PORT);
});
io.on('connection', function(socket){
console.log('A user has connected.');
});
//chat.html
//this is called right before </body>
<script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js'></script>
<script src='/socket.io/socket.io.js'></script>
<script src='/public/client.js'></script>
//client.js
var socket = io();
client.js is loaded as expected (and the console throws no errors) but i can't see 'A user has connected' as i'd expect.
You can check full source code here https://glitch.com/edit/#!/farlokko-advanced-node
Thanks.
UPDATE:
The problem was a wrong initialization of the passport.socketio module, which interfered with sicket.io . The main problem probably was a wrong store(memoryStore instead of mongo-store) and a wrong key for the cookie (express.sid instead of connect.sid).
Finally socket initialization was ok and had to be io.connect("host here").
As specified on the doc, you have to configure the client to connect to your localhost, and then, on the connection, you'll have your message :
<script>
var socket = io.connect('http://localhost'); // <--- HERE MAN
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>

expressJS and socket.io listening to different ports and socket.io client connect

So I have a nodejs application which uses socket.io and expressjs
I use port '3000' for the express app and port '8080' for the socket app
Is it possible to use the same port for both these services?(express and socket.io)
When i want to connect to a socket from the client, I use the following code:
var socket = io('http://localhost:8080')
whats the right way of connecting to it( I see various ways in tutorials across the internet) and have no clue.
Is it possible to use the same port for both these services?(express and socket.io)
yes
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(8080); //or 3000
When i want to connect to a socket from the client, I use the following code:
At the front end :
include socket.io lib
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080'); //or 3000
</script>
EDIT :
without express
var app = require('express').createServer();
var io = require('socket.io')(app);
app.listen(8080);
For more info socket.io
Yes, it is possible for both to use the same port. In fact, you should use the same port to make the client connect to your web socket when he sends a request. Socket.io docs has tutorial on how to connect with express.
Code from socket.io docs:
var app = require('express').createServer();
var io = require('socket.io')(app);
app.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
If you want to connect socket with express-generator generated template, you this:
stackoverflow post

Socket io heartbeat is not emitting

when i try to communicate with my socket io, the connection is established and the websocket writing is taking place, but the hearbeat is not getting emitted on the server ..so im not receiving anything on the client side. but when i disconnect and connect the server again, the old written message is getting emitted. please help me through this. thank you
I have tried with different port numbers, but its not working.
app.js (Server):
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log("Connected");
});
});
index.html (Client)
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
Socket.io might work unstable because of firewall or antivirus. This is actually a problem of WebSockets.
To solve this you may try to exclude WebSockets from the transports between client and server and specify on server side just XHR long polling and JSONP (as these two are the most stable):
io.set('transports', ['xhr-polling', 'jsonp-polling']);
I would also recommend to take a look at Engine.io. This framework is written by Socket.io author as the alternative, which works more stable.
The trick is following:
While Socket.io tries to connect via WebSockets first (when this attempt is fail, user will have to wait about 10 sec to switch to another transport), Engine.io tries to connect via XHR (which works in 100% cases), and meanwhile tries WebSocket connection, and if success - switching to WebSockets occurs.
Edit: Socket.io version 1.0+ is built on the top of Engine.io, so it has now all the benefits described above.

Connect to node.js socket.io server: clients don't connect - server reports" destroying non-socket.io upgrade"

I thought that socket.io would allow me to implement a websocket server. I have this very simple code:
// Require HTTP module (to start server) and Socket.IO
var http = require('http'), io = require('socket.io');
// start at port 8888
var server = http.createServer(function(req, res) {
res.writeHead(200,{'Content-Type': 'text\html'});
res.end('<h1>Welcome to the Notification Server</h1>');
});
server.listen(8888);
// Create Socket.io obj/pass to server
var socket = io.listen(server);
socket.on('connection', function(client) {
console.log('Successful Websocket connection!');
client.on('message', function(event) {
console.log("Received message from client", event);
});
client.on('disconnect', function() {
console.log('Client has disconnected');
});
});
I've tried a few different test clients all of which generate this message on the server: debug - destroying non-socket.io upgrade
One such client attempt has some code like this:
<html>
<script type="text/javascript">
<!---
window.WebSocket = window.WebSocket || window.MozWebSocket;
var ws = new WebSocket("ws://dev.ourserver.com:8888");
ws.onopen = function() {
alert("Connected");
}
ws.onerror = function(error) {
alert("Error:"+error);
}
// -->
</script>
<body>
</body>
</html>
As soon as we load the page I get the debug message on the server.
I thought the point of this library was to support the websocket protocol and any client supporting websockets would be able to connect.
If I interpret the message literally it seems to indicate that server.io has detected that it is connecting to a "non socket.io" client. Does this mean that there is no way for me to connect to this server without using socket.io in the client?

How to connect two node.js servers with websockets?

Here's my problem:
I have server A, running node.js and using socket.io for communicating with clients (web browsers). This all is running fine and dandy.
However, now that I have server B, which also needs to connect to server A through websockets, I have hit a wall. None of the node.js websocket clients I've found won't work with the socket.io on the server A.
So, this is the case I'm striving for:
.--------. .----------. .----------.
| CLIENT | <--> | SERVER A | <--> | SERVER B |
'--------' '----------' '----------'
Client-server A connection is done through socket.io
Now, Server B (running node.js) should connect to server A via websocket (in order to go through port 80). But...
Even the example code in socket.io-client module doesn't work... :/
// Connect to server
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected.');
});
The code just passes without any errors and execution ends after few seconds.
Update: Code samples
Server (which works just fine) looks like this:
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Client looks like this
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
1, 2 and 3 prints out just fine, no errors, and few seconds later the process just exits
Also, server A doesn't output anything to the log, even though I have the socket.io logging set on "everything".
For future people:
Here is 2 very simple Node.js apps that use socket.io to connect, send and receive messages between each other.
Required package is:
npm install socket.io
Node-App-1 server.js:
var io = require('socket.io').listen(3000);
io.on('connection', function (socket) {
console.log('connected:', socket.client.id);
socket.on('serverEvent', function (data) {
console.log('new message from client:', data);
});
setInterval(function () {
socket.emit('clientEvent', Math.random());
console.log('message sent to the clients');
}, 3000);
});
Node-App-2 client.js:
var io = require('socket.io-client');
var socket = io.connect("http://localhost:3000/", {
reconnection: true
});
socket.on('connect', function () {
console.log('connected to localhost:3000');
socket.on('clientEvent', function (data) {
console.log('message from the server:', data);
socket.emit('serverEvent', "thanks server! for sending '" + data + "'");
});
});
Turns out I was using old examples, for some reason, even though I triple checked them. Well, doh.
Also, it turned out that the socket.io-client is broken on latest Node (6.x.x). Managed to find an update from github for it, replaced the files and yay, everything's working!
Edit: Unfortunately I didn't save any links to working examples but after quickly skimming through the code it seems that the only changes were to the client code, which now looks like this:
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = io.connect('localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
Here is a snippet of code I wrote, it's using socket.io 1.0.6 and socket.io-client 1.0.6. The case is the following:
Server A (Socket.io Client) <---> Server B (Socket.io Server)
Server B (Server):
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res)
{
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket)
{
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Server A (Client):
console.log('1');
// Connect to server
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
If I'm using localhost:8080 only on the client server it doesn't connect.

Resources