Node.js chat app doesn't load - node.js

I just created a node.js chat app.. but the app doesn't load.
The code is very basic node.js chat app:
// Load the TCP Library
var net = require('net');
// Keep track of the chat clients
var clients = [];
// Start a TCP Server
net.createServer(function (client) {
console.log("Connected!");
clients.push(client);
client.on('data', function (data) {
clients.forEach(function (client) {
client.write(data);
});
});
}).listen(5000);
// Put a friendly message on the terminal of the server.
console.log("Chat server is running\n");
After I compile it, I write in the chrome browser localhost:5000 but the page is keep loading and never finish.
However, the following code works perfectly:
// Load the TCP Library
net = require('net');
// Start a TCP Server
net.createServer(function (client) {
client.write("Hello World");
client.end();
}).listen(5000);
I run Windows 7 64 bit on my computer, and I'm using chrome.
Thanks in Advance!

You are creating a TCP/IP server by using the net module, but you are accessing it using the http protocol using your web browser.
This does not match each other.
Try to connect to your server using telnet, e.g., and everything should be fine.
Alternatively, if you want to be able to connect using your webbrowser, you need to use the http module instead of the net module.

The net library if for TCP, not for HTTP. If you use TCS you should be able to access your chat with telnet but not with the browser.
This is an example on how write one for HTTP (from http://nodejs.org/)
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Don't test with browser when opening tcp connection.
Simply test with
telnet localhost 5000 in your console.

Related

Socket.io client doesn't connect to server

I have developed a simple chat using socket.io on a vagrant environment and it works correctly.
When I try to run the chat on the production environment, the nodejs/socket.io server runs but the client doesn't even fire the connect event.
The only thing I've modified is, in the client side:
var socket = io.connect('http://localhost:3000');
to:
var socket = io.connect('http://ip_address:3000');
This is the server code:
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
app.listen(3000, function() {
console.log('Server is running');
});
function handler(req, res) {
res.writeHead(200);
res.end('');
}
io.on('connection', function(socket) {
socket.on('subscribe', function() {
console.log('subscribe request has arrived');
console.log(socket.id);
});
});
If it worked locally and stopped working after deployment, it's probably a network issue - firewall, blocked port, linux enforcing or something of that sort.
To find the source, go to the host server and try connecting the port
telnet 127.0.0.1 3000
Did you get 'Connection refused' error? if so which server is running the code? make sure firewall service is either off or with exceptions for port 3000. on linux check enforcing .
If the connection succeed, test the connection from your local pc
telnet ip_address 3000
If it fails than test access to external service (for example portquiz.net) This way you will know if the issue is with your local pc or network, or the remove server.

Azure free website NodeJS websocket no longer connecting

I have an Android app that uses websockets via a NodeJS server hosted with Azure. For the passed six months, everything has been fine. Today, all is not fine. When I try to connect to my server, I get the response "No address associated with hostname."
I have websockets enabled in my config tab in the management console, also in the web.config file so that Node handles the websocket and not iis. I have changed nothing, toggled the websocket settings, nothing works. I have restarted the server many times. I also created a new website and migrated everything, still the same issue. I cannot get tech support from Microsoft because the website is a free one. I am aware that there is a max of 5 connections to the websocket; this is not the issue.
My server is using the 'ws' websocket module. I have taken my server.js code down to the minimum for testing. This is it now...
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: process.env.PORT || 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {});
ws.on('close', function closing(code, message) {});
if (ws.readyState == 1)
ws.send('message from the server!');
});
It still does not work. I replaced the entire file with the code below and the server responds with text in the browser. Of course, this is not websocket, but it shows that the server is able to respond to http requests.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('Hello, world!');
}).listen(process.env.PORT || 8080);
Has anything changed with the usage of websockets? Have recent restrictions been placed I am unaware of?

Create web socket streams between a server and arbitrary NodeJS processes

Having a server running on localhost:5000, I want to connect to that server from another NodeJS process, via web sockets.
From my experience with web sockets, I always needed the server object to create a web socket server.
var http = require('http');
// create http server
var server = http.createServer(function(req, res) {
// serve files and responses
...
});
// Socket.io server listens to our app
var io = require('socket.io').listen(server);
// Send current time to all connected clients
function sendTime() {
io.sockets.emit('time', { time: new Date().toJSON() });
}
// Send current time every 10 secs
setInterval(sendTime, 10000);
// Emit welcome message on connection
io.sockets.on('connection', function(socket) {
socket.emit('welcome', { message: 'Welcome!' });
socket.on('i am client', console.log);
});
server.listen(3000);
This is a tiny example using socket.io. Without having access to get the server variable (since this server will be deployed some where in the cloud), how can I connect via web sockets to this server?
An ugly solution would be via HTTP requests, but that's not web sockets. I want to keep the connection open and pipe data there.
How can I do that?
You get the socket.io-client module, require() it into your other nodejs server and use that client module from your other server (which will be the client in this case) and connect from that server to this one.
Example code here: https://github.com/automattic/socket.io-client
var socket = require('socket.io-client')('http://localhost');
socket.on('connect', function(){});
socket.on('event', function(data){});
socket.on('disconnect', function(){});

Server showing multiple client connection (net nodejs)

I am trying to make a server which listens on a internet facing port and forwards incoming http requests to an internal express server listening at another port. Following is the relevant part of the code I'm using.
var net = require('net');
var server = net.createServer();
server.listen(addr.from[3], addr.from[2], function(){
console.log('Server listening');
});
server.on('connection',function(from){
console.log('Client connected from '+ from.remoteAddress);
var to = net.createConnection({
host: addr.to[2],
port: addr.to[3]
});
from.pipe(to);
to.pipe(from);
from.on('error',function(err){
winston.error('Error at unix box'+err);
to.end();
});
to.on('error',function(err){
winston.error('Error at middleware server'+err);
from.end();
});
from.on('end',function(){
console.log('Client disconnected ');
to.end();
});
to.on('end',function(){
console.log('Middleware disconnected');
from.end();
});
});
The problem I'm encountering is that, when I open "ip:port" in the browser (which would be the internet facing port) I'm getting messages multiple "client connected from xxxxxx" msgs on the console. Can anyone help me understand why this is happening?
Whenever browser connects to a website it usually makes two requests: normal and to retrieve favicon.
Funny thing, is that the favicon request is not even displayed in browser developer tools.
To verify, you need to extract the request made, print it to server, and then observe why you get multiple requests. For that, connection might be too early, try hooking request event instead:
server.on('request', funtion(req, res) { console.log(req.url); });

Socket.io 0.7.9 connection issues

I am attempting to upgrade to socket.io 0.7.9 and have run in to problems.
I have used the basic example from the socket.io homepage. My server is:
var http = require('http'),
url = require('url'),
https = require('https'),
fs = require('fs'),
crypto = require('crypto'),
io = require('../'),
sys = require(process.binding('natives').util ? 'util' : 'sys'),
server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end();
});
server.listen(80,"[MYIP]");
var io = io.listen(server), buffer=[];
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
It connects OK on some computers but not on others. It is the same across all browsers.
Does anyone know why this would happen? Could there be some local networking issue that causes this?
UPDATE
It appears that the people who are unable to connect from their computers are running anti virus with real time web shields that seem to block the connection. When they turn it off, it connects OK on some browsers...
I have been using socket.io and node.js for the last two months and some issues like yours happened to me too.
Firewalls are often a problem with the port 80, especially when used with a DNS (like in a corporate network) because they will temper with the headers of the socket packages. One work around could be to try another port.
My application has an apache server on the port 80 and my websocket is on the port 843, everything is working fine on Firefox and Chrome.
You can use the xhr-polling fallback option to bypass this type of errors by adding this script:
io.set('transports', ['websocket','xhr-polling']);
xhr-polling offers less real-time performance, but is really dependable and works on most browsers and network configurations.
I hope this will help you!

Resources