socket.io not connecting for client - node.js

It is simple chat app using node.js and socket.io. This app work fine in my local computer but do not work when I upload it to the server: Please look at my code on remote server and the problem.
Here is the code snippet of client:
<script type="application/javascript">
var socket = io.connect();
eventHandler(socket);
function eventHandler(socket) {
socket.on('connect', function(){
socket.emit('adduser', prompt("What's your name?"));
});
socket.on('error', function () {
console.log("Connection error"); //It works after a few second with error
});
}
$(document).ready(function(){
.....
});
</script>

It looks like on the remote server Socket.IO 0.9.16 is installed (which is not up-to-date). If you're writing code according to new documentation this might be a reason why it doesn't work as you expected.
Try to upgrade Socket.IO to 1.0

This change worked for me:
you wrote this method:
var socket = io.connect();
Thanks to another help page, I switched this method to this:
var socket = io.connect('http://localhost:8080');
You can replace "localhost" with whatever ip address you use to access your server.
Also, just in case - if you haven't, it would be useful to include a connection notification on your server in the app.js file. mine looks like the following:
var fs = require("fs")
, http = require("http")
, socketio = require("socket.io");
var server = http.createServer(function(req, res) {
res.writeHead(200, { "Content-type": "text/html"});
res.end(fs.readFileSync(__dirname + "/index.php"));
}).listen(8080, function() {
console.log("Listening at http://localhost:8080");
});
socketio.listen(server).on("connection", function(socket) {
console.log("CONNECTED");
socket.on("message", function(msg) {
console.log("Message received: ", msg);
socket.broadcast.emit("message", msg);
});
});
You can also see the help page I linked to in case they have something that more closely relates to your issue.

Your page seems to be working for me. Make sure your page is fully loaded before executing your script. This is done by using window.onload like this:
<script>
window.onload = function() {
//Your code here
}
</script>

Related

Node.js WebSockets Send Message

I'm trying to come to terms with how WebSockets work in Node.js but I'm having some trouble with sending a message.
I have my WebSocket server configured as follows (index.js)
var ws = require("ws");
var wsserver = new ws.Server ({
server: httpserver,
port: 3030
});
wsserver.on (
"connection", function connection(connection) {
console.log("connection");
}
);
wsserver.on (
"open", function open(open) {
console.log("open");
}
);
wsserver.on (
"message", function message(message) {
console.log("message");
}
);
This seems to be working ok because I can establish the connection using
var wscon = new WebSocket("ws://192.168.20.88:3030");
Which then gives me the connection output on the server. If I try to use send though nothing seems to happen and no error messages
wscon.onopen = function(open) {
wscon.send("test message");
}
I must be missing something but I don't know what
I might have an answer for this but I'm not entirely sure just yet, I'm going to put this here just in case.
I think the problem is that the message listener is added to the wrong object (the server object), I tried to add the message listener to the connection object passed to the server and it seems to be working but I'm not 100% sure why
wsserver.on (
"connection", function connection(connection) {
console.log("connection");
connection.on (
"message", function message(message) {
console.log("message : " + message);
}
);
}
);
Which dependency works for me?
I have been using socketIO for a while now and it works perfectly for Node.JS API's / servers. There are millions of tutorials online for this framework and I'll tell you one them.
How to install?
If you use NPM as your package manager in Node.JS just down it with the following command:
npm install --save socket.io
In case you're using yarn you can install socketIO as following:
yarn add socket.io
Setup the socket server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
// Used for serving the HTML page (if used)
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
// Listen for new connections
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Now in index.html I add the following snippet before the :
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
In your front-end you are able to fire of an event via the socket by calling the following function / code:
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
</script>
In our case we emitted an event called chat message. So in order to receive the value send over the socket connection we call the following code in our backend / api:
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
and that is basically how you use socket with the library SocketIO. Hope this helped fixing your issue!

How to properly setup socket connection from AS3 air to nodejs

I found lot of samples in here, but very old posts using very old node and adobe air versions. I made simple node js server which is working properly - tested with web browser. Node JS is version 6.11.
var http = require('http');
var sockets = [];
var server = http.createServer(function(req, res) {});
server.listen(8080);
var io = require('socket.io').listen(server);
io.set('transports', ['websocket','flashsocket']);
io.sockets.on('connection', function (socket) {
sockets.push(socket);
socket.on('disconnect', function() {
var i = sockets.indexOf(socket);
sockets.splice(i, 1);
});
socket.on("data",function(d){
console.log('data from flash: ',d);
});
socket.write(JSON.stringify({message:"blah blah"}));
});
My task is to connect it to AS3 Air application. Script looks something like this:
public class CustomSocket extends Socket {
public function CustomSocket(host:String = null, port:uint = 0) {
super();
configureListeners();
if (host && port) {
super.connect(host, port);
}
}
private function configureListeners():void {
addEventListener(Event.CLOSE, closeHandler);
addEventListener(Event.CONNECT, connectHandler);
addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
}
....
}
It is connecting to socket with no error, but neither sending or receiving data are working. Only connecting event is fired and that's it. ProgressEvent.SOCKET_DATA is never fired. Also, on connect I send some data to node, never received.
Any idea?
Figured it out. Instead of using socket.io, like for web pages, I had to use TCP socket connection on nodejs side. When I create script like this:
var net = require('net');
var net_server = net.createServer(function(socket) {
socket.write('blah blah \n');
socket.on('data', function(chunk) {
});
socket.on('error', function(err) {});
});
net_server.listen(8000);
there is bi-directional communication which is working.

using socket.io with cordova and IOS device

I'm trying to use this simple tutorial:
http://socket.io/socket-io-with-apache-cordova/
My node.js is working fine and i'm emulating to iOS without problem, but the socket.io isn't working, here is my javascript(the same way as the tutorial above):
app.initialize();
document.addEventListener('deviceready', function() {
console.log(socket);
socket.on('connect', function() {
socket.on('text', function(text) {
alert(text);
});
});
});
and one more thing how can i get this console.log to debug?
here is how i'm getting socket.io(the same way as the tutorial above):
<script type="text/javascript" src="http://cdn.socket.io/socket.io-1.0.3.js"></script>
here is my server.js(the same way as the tutorial above):
var server = require('http').createServer();
var io = require('socket.io')(server);
io.sockets.on('connection', function (socket) {
console.log('socket connected');
socket.on('disconnect', function () {
console.log('socket disconnected');
});
socket.emit('text', 'wow. such event. very real time.');
});
server.listen(3000);
I think, that the problem and the tutorial didn't told is how i would connect my cordova app with port 3000
I made it, this tutorial is very good but it's not totally right.
You have to connect the socket to your server first (i'm using localhost and port 3000, but if you're using some server outside, i think you've to just put the ip and port):
var socket = io.connect('http://localhost:3000');
and after that, you call "socket.io", here is my complete code:
document.addEventListener('deviceready', function() {
var socket = io.connect('http://localhost:3000');
socket.on('connect', function() {
socket.on('text', function(text) {
alert(text);
});
});
});
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
var socketHost = "http://localhost:3000";
var socket = io.connect(socketHost);

var socket = io.connect('http://yourhostname/');?

I try socket.io again since v.1.0 released.
As the doc,
https://github.com/Automattic/socket.io
Server side:
var server = require('http').Server();
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.on('event', function(data){});
socket.on('disconnect', function(){});
});
server.listen(5000);
Client side
var socket = io.connect('http://yourhostname.com/');
In development, surely
var socket = io.connect('http://localhost:5000/');
It works, but I'm very uncomfortable with hardcoding the hostname(subdomain.domain) in the client code(/index.js).
The index.js is hosted by the http-sever and the socket.io is bundled to the http-server in this configuration.
Is there any smart way not to hardcode the hostname but to code in some relative path?
Thanks.
EDIT:
When I try:
var socket = io.connect('./');
The connection error:
GET http://.:5000/socket.io/?EIO=2&transport=polling&t=1401659441615-0 net::ERR_NAME_NOT_RESOLVED
is like this, so at least the port number (5000) is obtained properly without hardcoding in the client side.
Final answer.
I have totally forgotton that we can obtain the current url/domain in browser.
window.location.hostname
So, simply goes:
'use strict';
/*global window, require, console, __dirname, $,alert*/
var log = function(msg)
{
console.log(msg);
};
log('init');
$('document').ready(function()
{
var io = require('socket.io-client');
var socket = io.connect(window.location.hostname);
socket.on('connect', function()
{
log('socket connected');
});
});
You have to remember that Node.js is not a web server. It's a platform. When you specify a relative path, it doesn't know that you mean "relative to the current domain."
What you need to do is send the domain to the client when you send them the webpage (I don't know the specifics of your setup, but perhaps using a template variable?), and send them the localhost:5000 domain if you're in development, or your real domain if you're in production (alternatively, you can use a library like nconf, but you get the idea).
dunno, so far I did as follows:
'use strict';
/*global window, require, console, __dirname, $,alert*/
var log = function(msg)
{
console.log(msg);
};
log('init');
$.getJSON("../config.json", function(data)
{
var host = data.url;
var port = data.port;
$('document').ready(function()
{
alert(host + ':' + port);
var io = require('socket.io-client');
var socket = io.connect(host);
socket.on('connect', function()
{
log('socket connected');
});
});
});
It's browserified with socket.io-client.

cannot get client server running using express in node.js

hey i just started tinkering with node.js and am a complete noob. i am trying to get a simple client server communication going using socket.io and express (i have never used these before).
here is my code for the app(app.js):
var sys = require('sys'),
express = require('express'),
app = express('localhost');
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.send('Hello World');
});
app.listen(3000);
var socket = require('socket.io').listen(server);
socket.on('connection', function (client){
// new client is here!
setTimeout(function () {
client.send('Waited two seconds!');
}, 2000);
client.on('message', function () {
}) ;
client.on('disconnect', function () {
});
});
and here is my code for the client(client.html):
<html>
<p id="text">socket.io</p>
<script src="/socket.io/socket.io.js"></script>
<script>
$(document).ready(function(){
var socket = new io.Socket(),
text = $('#text');
socket.connect();
socket.on('connect', function () {
text.html('connected');
});
socket.on('message', function (msg) {
text.html(msg);
});
socket.on('disconnect', function () {
text.html('disconnected');
});
});
</script>
i got most of the code from:
NodeJS + socket.io: simple Client/Server example not working
and the changed it to be compatible with express 3.x
however when i run the server and open my client using chrome it tells me that it is unable
to load resource file:///socket.io/socket.io.js
i have already installed express and socket.io using npm
also i have read through atleast 20 similar posts and have not been able to find an answer
please help me. thank you
socket.io.js file needs to be served from port 3000, like localhost:3000.
So here is what you do change
<script src="/socket.io/socket.io.js"></script> to
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
Are you opening the client.html page directly from the local file system? The request for socket.io.js should look like http://localhost/socket.io/socket.io.js not file:///socket.io/socket.io.js.

Resources