socket.io client to server confusion - node.js

I'm trying to make a simple IRC to get to understand how things work. I've set up a local node server and another workspace to connect to localhost, they talk just fine. However when I push the local server to Openshift and try to connect to it with the client with;
var socket = io.connect("http://irc-abc.rhcloud.com:3000");
It's not connecting.
What am I doing wrong here and or how can I make this work?
NOTE: I'm new to websockets and I'm trying to understand them, I'm probably missing the big picture.
Yes I did find a lot of similar questions on stackoverflow however it did not help me, as I said I'm fairly new with websockets and have some trouble understanding it.
server
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var ip = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
// TO-DO verify creds against db
var credentials = {
'username' : ''
};
io.on('connection', function(socket){
// verify if client has username
socket.on('login', function(credentials){
if(credentials.username) {
this.username = credentials.username;
console.log( this.username + ' connected');
io.emit('notice', this.username + ' connected');
}
else {
console.log( 'USER GOT DENIED' );
socket.disconnect();
}
// when message received
socket.on('chat message', function (msg) {
var message = this.username + ': ' + msg;
io.emit('chat message', message);
});
});
// when user disconnects
socket.on('disconnect', function(){
console.log( this.username + ' disconnected');
});
});
http.listen(port, ip);
console.log('listening on ' + ip + ':' + port);
Client
var socket = io.connect("irc-abc.rhcloud.com:3000");
var username = '<?php if(isset($_SESSION['username'])) echo $_SESSION['username'];
else echo 'guest'; ?>';
var credentials = {
'username' : username
};
socket.emit('login', credentials);
$('form').submit(function() {
if ($('#m').val()) {
socket.emit('chat message', $('#m').val());
$('#m').val('');
}
window.scrollTo(0,document.body.scrollHeight);
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
window.scrollTo(0,document.body.scrollHeight);
});
socket.on('notice', function(notice){
$('#messages').append($('<li>').text(notice));
window.scrollTo(0,document.body.scrollHeight);
});

The first thing I'd do is check if port 3000 is firewalled. Some (most) hosts firewall all ports that are not normally used (80, 443, etc). If you can't get them to change the firewall right away, test with port 80.

Related

Talking AWS Servers (EC2)

I am trying to get two EC2 instances to talk; but, I am running into a block. I am not sure what IP address and port to use, and also am wondering if I need to change any of the server/client code now that they aren't talking on the same machine. Security Groups are allowing inbound traffic on ports 22,80, and 60201.
When I use port 60201, i get EADDRNOTAVAIL.
Here is the config file.
Host wmnode
User ubuntu
IdentityFile ~/.ssh/wmnode
HostName 52.4.212.112
Host mvclient
User ubuntu
IdentityFile ~/.ssh/mvclient
HostName 107.21.65.254
Here is server.js
const port = 60201;
const ipAddress = "52.4.212.112"
var http = require('http');
var io = require('socket.io');
var server = http.createServer();
server.listen(port, ipAddress);
var socket = io.listen(server);
socket.on('connection', (serverSocket) => {
console.log('connected to 52.4.212.112');
serverSocket.on('clientEvent', function (data) {
console.log('message from the server:', data);
serverSocket.emit('serverEvent', "thanks for sending '" + data + "'");
});
});
And here is client.js
const port = 60201;
const ipAddress = "52.4.212.112";
const url = 'http://' + ipAddress + ':' + port;
var io = require('socket.io-client');
var socket = io(url);
socket.on('connect', () => {
socket.on('serverEvent', function (data) {
console.log('new message from the server:', data);
});
setInterval(function () {
socket.emit('clientEvent', Math.random());
console.log('message sent from the client');
}, 3000);
});

Node.js express websocket not broadcasting to all connected clients

Im trying to create a node websocket for messaging and broadcasting using openshift. Below is my code.
var WebSocketServer = require('ws').Server;
var http = require('http');
var ipaddr = opneshift_ip;
var port = openshift_port;
var server = http.createServer();
var wss = new WebSocketServer({server: server, path: '/connectserv'});
wss.broadcast = function(data) {
for(var i in this.clients) {
console.log(this.clients[i]);
this.clients[i].send(data);
}
};
wss.on('connection', function(ws) {
console.log('a client connected');
ws.on('message', function(data) {
console.log('>>> ' + data);
ws.send('got '+data);
if (data == 'broadcst') {
console.log('broadcst');
wss.broadcast('Hi All');
}
});
ws.on('close', function() {
console.log('Connection closed!');
});
ws.on('error', function(e) {
console.log(e);
});
});
console.log('Listening at IP ' + ipaddr +' on port '+port);
server.listen(port,ipaddr);
When any client connects, console writes "a client connected".
When any client sends message, console writes ">>> message" and im getting the same at client as well ("got message")
But when multiple clients are connected, if i want to broadcast a message to all connected clients, i send "broadcst" as message. Than goes into
if (data == 'broadcst') {
console.log('broadcst');
wss.broadcast('Hi All');
}
But only the client which sends get the message.
How to make all clients to get the message?
Does each client creates separate session?
How to use redis here?
Any quick help appreciated.
Thanks.
Try
wss.broadcast = function(data) {
for(var i in wss.clients) {
console.log(wss.clients[i]);
wss.clients[i].send(data);
}
};
broadcasting with wss

socket.io net::ERR_CONNECTION_TIMED_OUT

I'm testing with socket.io and unity.
In my localhost (my pc) did walk perfectly but now I got all on my hosting to see how it works online and i have the following problem:
url app online: http://almightysystem.com.ar/UnityApps/UnityChatSocket.io/
I have this loop error:
GET http://almightysystem.com.ar:29011/socket.io/?EIO=3&transport=polling&t=1423454072758-3 net::ERR_CONNECTION_TIMED_OUT
server.js:
var express = require('express');
var port = process.env.PORT || 29011;
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static(__dirname + '/public'));
io.on('connection', function(socket){
socket.on('chat message', function(message){
io.emit('chat message', message);
});
});
http.listen(port, function(){
console.log('Express server listening on port ' + port);
});
client.js:
//SOCKET.IO
var socket = io.connect('http://almightysystem.com.ar:29011/');
socket.on('chat message', function(message){
SendMessage ('ChatSystem', 'GetChatMessage', message);
console.log("Mensaje recibido del Servidor hacia Unity: " + message);
});
function UnitySendMessage(message){
socket.emit('chat message', message);
console.log("Mensaje de Unity al Servidor: " + message);
}
Any idea?
I have an answer to this problem.
In your client code.
// SOCKET.IO
var socket = io.connect('http://almightysystem.com.ar:29011/');
socket.on('chat message', function(message){
SendMessage ('ChatSystem', 'GetChatMessage', message);
console.log('Mensaje recibido del Servidor hacia Unity: ' + message);
});
function UnitySendMessage(message){
socket.emit('chat message', message);
console.log('Mensaje de Unity al Servidor: ' + message);
}
Remove the port number in the connect function.
var socket = io.connect('http://almightysystem.com.ar:29011/');
Like this.
var socket = io.connect('http://almightysystem.com.ar');
In your server code, you should use server.listen(port, ...) and not app.listen(port, ...) because app.listen() creates a new http server and attaches to that, which you do not want because you already have one (server).
Also, in your client code, you should use io.connect('http://almightysystem.com.ar:29011/'); instead of io.connect('http://almightysystem.com.ar/UnityApps:29011'); because the socket.io server won't know to listen on /UnityApps (because you're not passing a config object (with path set) to the socket.io server constructor), even after you've moved the :29011 part to the right place.
I had the same problem and solved it using
var socket = io.connect();
instead of
var socket = io.connect('http://almightysystem.com.ar:29011/');
Try this on your client side const socket = io("http://almightysystem.com.ar:29011/", { transports: ["websocket"] }); to specify you want to use websockets

Why does the Socket Server stops working?

I am creating a WebSocket for an online game. I have some code that works perfectly, but after a time the server stops the Socket. I don't know what can be wrong and I don't have an error or something. It just stops running.
Does anyone know what can be wrong with this code?
var mysql = require('mysql');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var cookies;
var db = mysql.createConnection({
host: 'hostname',
user: 'username',
password: 'password',
database: 'database',
port: 3306
});
db.connect(function(err){
if (err) console.log(err)
});
function createCookie(name,value,days, socket) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
socket.handshake.headers['cookie'] = name+"="+value+expires+"; path=/";
}
function readCookie(name, socket) {
var nameEQ = name + "=";
var ca = socket.handshake.headers['cookie'].split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name, socket) {
createCookie(name,"",-1, socket);
}
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('chat message', function(msg){
if(readCookie('uid', socket) != null) {
db.query('SELECT * FROM ww_user_settings WHERE usr_set_id = '+readCookie('uid', socket)+' AND usr_set_setting_id = 23').on('result', function(data){console.log('Message from '+data.usr_set_value+': '+msg);io.emit('chat message', data.usr_set_value+": "+msg);});
}
else {
console.log('Unauthorized message sent.');
socket.disconnect('unauthorized');
}
});
});
http.listen(44444, function(){
console.log('listening on *:44444');
});
As I said, the Socket works. But after a time, even when nothing special happens, the Socket stops running on my Windows 2012 Server.
The problem here was that the server lost the connection with the MySQL Server. By losing it, it will stop working.

How to receive log from SRCDS in node.js

I have srcds (source dedicated server)
at console add logaddress_add 0.0.0.0:25001
this turn on sending the log to the remote server
tried to catch the log in this way
var net = require('net');
var server = net.createServer(function(c) {
c.on('end', function() {
console.log('server disconnected');
});
c.pipe(c);
});
server.listen(25001);
and that
var net = require('net');
var client = net.connect({port: 25001});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('client disconnected');
});
and that
var s = dgram.createSocket('udp4');
s.bind(25001, function(data) {
console.log(data)
});
no result. can someone help?
thanks in advance
[solved]
at SRCDS server
logaddress_add 0.0.0.0:8006 //for local ip
at app.js
var dgram = require('dgram'),
server = dgram.createSocket('udp4');
server.on('message', function (message, rinfo) {
var msg = message.toString('ascii').slice(5,-1);
console.log(msg);
});
server.on('listening', function () {
var address = server.address();
console.log('UDP Server listening ' + address.address + ':' + address.port);
});
server.bind(8006);
I ended up writing a little library to do this (srcds-log-receiver), which validates the packet format, extracts out the date and allows you to use the sv_logsecret function to put a small amount of authentication on the connection, since UDP packets are easily forged.
I also wrote a parser to turn those log lines in to useful objects.

Resources