socket.on does not work in Node.JS (clientside) - node.js

My socket.on code does not work on the clientside, but on the serverside.
I have 2 pages, one to socket.emit(so I can call it whenever I want to) and one (the main/index page) to listen for the emit socket.on.
Servercode:
var io = require('socket.io').listen(app.listen(8080));
io.on('connection', function (socket) {
socket.on('playerData', function(data) {
console.log(data);
});
});
Clientcode:
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script>
var socket = io('http://localhost:8080');
socket.on('playerData', function(data) {
console.log(data);
});
</script>
I am using Node.JS - Jade, Express, Socket.io (and AngularJS, but not in this part of the code)
As already mentioned, the Serverside console.log is being called when I call my emit function, but on the Clientside nothing happens.
Currently using Chrome as my browser.

Related

socket.io emit to one client not working

I'm using socket.io 1.7.3 version. Server code:
io.on('connection', function (socket) {
console.log(socket.id); // CdnNBVe9ktJmMcb1AAAA
socket.to(socket.id).emit('something');
socket.emit('something'); // if I do it without to, it works but to all clients
console.log(socket.rooms); // { CdnNBVe9ktJmMcb1AAAA 'CdnNBVe9ktJmMcb1AAAA' }
});
Client:
<script src="/socket.io/socket.io.js"></script>
var socket = io.connect(..);
socket.on('connect', function() {
console.log(socket.id); // CdnNBVe9ktJmMcb1AAAA
socket.on('something', function() {
alert('it works');
});
});
Why it doesn't work? I'm not getting any alert although all console.logs seems to be correct.
To send a message to the particular client, you must provide socket.id of that client to the server and at the server side socket.io takes care of delivering that message by using,
socket.broadcast.to('ID').emit( 'send msg', {somedata : somedata_server} );
In your code
socket.broadcast.to(socket.id).emit('something');

How to call functions in socket.io?

Hello guys this is my code in the server side of socket.io and I don't know how to call this functions in the client side. Can you help me or provide me the code on how to call this functions:
io.sockets.on('connection', function (socket){
sub.on('subscribe', function (channel) {
pub.publish('Privatex','Test Message 1');
pub.publish('Privatex','Test Message 2');
pub.publish('Privatex','Test Message 3');
});
sub.on('message', function (channel, message) {
console.log(channel + ':' + message);
sub.unsubscribe();
pub.end();
sub.end();
});
sub.incr('Channel Test');
sub.incr('Privatex');
});
Please consult the How-To-Use section first.
To invoke this code on client side, you simply have to use this code, assuming socket.io is already configured on server side.
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');//path to socket.io
</script>
But let' take two minutes to see what's going on : this will be invoked on EVERY client connection because it's directly under the connection event. It's sometimes not the best way to do this (because a client can be briefly disconnected), and it's better to emit events from the client.
client code
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');//path to socket.io
socket.emit('my other event', { my: 'data' });
</script>
server code
io.sockets.on('connection', function (socket) {
socket.on('my other event', function (data) {
//do something here
});
});

Access is forbidden for Node.js

I am trying to create a simple chat application using Node js. I am using a Windows operating system. As local server I am using Xampp. I have installed Node. I have also installed socket.io using package.json. The code in package.json is given below.
{
"name":"chat",
"version":"0.0.1",
"private":"true",
"dependencies":{
"socket.io":"0.9.16",
"express":"3.4.0"
}
}
Then I have written the code for the server. The Node server is running in port 1337. The code for the server is given below.
var io = require('socket.io').listen(1337);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Then when I run it, it is running. Then I have written the code for the client in a index.php file. The code for the client is given below.
<!DOCTYPE html>
<html>
<head>
<title>Chat app.</title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="/node:1337/socket.io/socket.io.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var socket = io.connect('http: // localhost / node : 1337');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
});
</script>
</body>
</html>
But when I try to the run it with a browser, all I get see in the console is that access is forbidden. All my files including node_modules is saved in C:\xampp\htdocs\node.
The code you're using is copied from the socket.io Home page and it's only used as an example, but it's not actually working code because the socket.io script isn't being bound to any server instance.
Socket.io isn't a server. It's just a library for nicely handling Websockets. In order to use socket.io you have to require HTTP or Express and create a server instance. Then you'll have to bind the server instance with socket.io.
For a working implementation on how to get socket.io up and running with your server, you'll have to look at the How To Use page. There they have these nice code example, depending on the implementation you're running (if it's HTTP, or something else).
So scratch the whole Xampp server idea. Node has it's own built in server capabilities and that's what you're meant to be using.
Here's a working example (from the socket.io website) of how Socket.io is meant to be used with HTTP. In this code snippet, the server is also created (and it's listening on port 80), so you won't have to worry about that:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Once your server's up and running, you can access it by typing localhost:80 into the browser.

Can't find socket.io for client when server is created without handler

Browser can't find socket.io.js for client:
<script src="/socket.io/socket.io.js"></script>
When server is created without handler:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs');
app.listen(80);
//without this part:
/*function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}*/
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
I don't need and don't want handler function because everything I generate in PHP. And sometimes use client application functions for another file than index.html/php
So how to make browser can find socket.io.js?
I've wrote a demo app that you could have a look at if you don't want to loose to much time getting started with socket.io and Express 3.
To have websockets working your client js needs to be delivered from a webserver. This is one of those many browser limitation.
The easiest setup is to have a node server that provide both the client side Js and the WebSockets. Using easier the http module of Express (a bit overkill but super practical if you want to build something more than just a test app).
Other wise you need to have your client side js pointing to the right place. For example if you run your socket.io server of port 8080 and you deliver your static client side on port 8000 (using python -m SimpleHTTPServer for example or port 80 using a regular apache).
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
If you don't need access to http module functionality use this way:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Include this on your client side !
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
var io = io.connect();

Unable to receive events in SOCKET.IO client

I am new to socket.io and i am trying out the examples mentioned on their site. I am going good with it but problem occurs when i try to use io.emit on the server side and try to receive on client side.
Here is my server code
var io=require("socket.io").listen(8888);
io.set('log level',1);
io.on('connection',function(socket){
socket.emit('hi');
console.log("Connected");
});
And my client's code
<script src="http://localhost:8888/socket.io/socket.io.js"></script>
<script>
var socket=io.connect("http://localhost:8888");
socket.set('log_level',1);
socket.on('hi',function(){
console.log('received');
});
</script>
The problem is i don't see the message 'received' in the console! The answer may be trivial but i tried experimenting but failed everytime. Please guide....
I am on ubuntu firefox. node version: 0.8.7
So you should have this on the serve side:
var io = require('socket.io').listen(88888);
io.set('log level',1);
io.sockets.on('connection', function (socket) {
socket.emit('hi);
console.log("Connected");
});
});
And you should have this on the client side:
<script src="http://localhost:8888/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8888/');
socket.set('log_level',1);
socket.on('hi', function () {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
WebSockets like many html5 features does not work in a non webserver environment. I mean It won't work if you are accessing your client with the file protocol.
You need to have a http server.
What I do to get things done easily, I use python built-in web-server. It does the job.
Just spawn it in you client folder like this:
python -m SimpleHTTPServer
And then point your browser to port 8000 (default).
I've made a boiler plate socket.io app that you can clone and even push directly to dotCloud.com
This is a simple example and could help you to get started with socket.io.
Look for examples on the soket.io GitHub page.
You wrote: io.on('connection' instead io.sockets.on('connection'
This code should work fine:
var io = require('socket.io').listen(8888);
io.set('log level', 1);
io.sockets.on('connection', function(socket){
socket.emit('hi');
console.log("Connected");
});

Resources