So i was trying to set a new project with nodejs and socket.io
at first i try these codes in my home pc at this site: http://socket.io/#how-to-use
i tried the first example and it works well so i continue my work at my home pc.
but, when i try it at my work pc my work is not working.
even the first example at the web doesn't work.
the client doesn't receive the emitted 'news' event from the server
and the client doesn't emit 'my other event' to the server.
there's no error at the client browser and i already try at all browsers i use (firefox, ie, and chrome all of them are the latest version)
why does the client doesn't emit the event to server, and the client can't receive emitted data from server?
what is the problem? is it the computer at my work? because i already tried it with 3 different computer, and the result is still the same. it only work at my home pc.
and at my work computer (win7 x86) i already disable my UAC and firewall.
i use nodejs v0.10.1, socket.io v0.9.13
here's the code that i copied from the example from socket.io:
client.html
<script src="./node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8999');
setTimeout(function(){
socket.emit('my other event', { my: 'emitted by timeout' }); // nothing happened at server
},3000);
socket.on('news', function (data) {
console.log(data); // this won't fire
socket.emit('my other event', { my: 'data' }); // this won't fire
});
</script>
server.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8999);
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);
});
});
output from node console:
info - socket.io started
debug - client authorized
info - handshake authorized c3Y6q0EnyWtldKBKnUHp
debug - setting request GET /socket.io/1/websocket/c3Y6q0EnyWtldKBKnUHp
debug - set heartbeat interval for client c3Y6q0EnyWtldKBKnUHp
debug - client authorized for
debug - websocket writing 1::
debug - websocket writing 5:::{"name":"news","args":[{"hello":"world"}]}
Related
my friend and I are both using the same wifi network with open ports for both of us. My friend is listening on port 8000 and I'd like to send him a message.
How can I achieve that using node and socket.io ? Thanks a lot
There are many ways to setup a simple messenger, the standard one is to setup a single socket.io server either on your or your friend's machine, something like this:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(8000);
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.on('connection', function (socket) {
console.log("user connected!")
socket.on('message', function (message) {
//Sends message to all connected sockets
socket.broadcast.emit("message")
});
});
Then your index.html should have some code for connecting to server and sending messages:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://server-ip-or-domain-name:port');
socket.on('message', function (message) {
//processing incoming message here
console.log(message);
});
function sendMessage(msg){
//sends message to server
socket.emit("message", msg);
}
</script>
In this setup both you and your friend should be able to reach the server machine. Use pings for debuging.
p.s. havent tested the code above, but that's the idea.
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');
Using the following simple application of socket.io, I get very strange behaviour, but only on some computers I tested. On most computers, it seems to work fine. This is the setup I used:
server.js:
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) {
i = 0;
setInterval(function() {
socket.emit('news', 'test');
}, 200);
socket.on('my other event', function (data) {
console.log(data);
});
});
index.html:
<html>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('news', function (data) {;
console.log("test");
socket.emit('my other event', { my: 'data' });
});
</script>
</html>
<body></body>
If I set the interval on 30 instead of 200 milliseconds, it seems to work well (i.e. the client and server both receive the socket messages on time), but when I set the interval on 100 or more milliseconds, the client does not respond to the first 13 (consequently 13) messages sent by the server and then suddenly receives all 13 messages at once, directly followed by this error:
"WebSocket connection to 'ws://example.com/socket.io/1/websocket/63zOWQ5mEuzV01WuqZ5X' failed: Unrecognized frame opcode: 11".
This behaviour repeats for some time, so sets of 13 messages are suddenly received followed by the error, but sometimes, after a random amount of error sets, it starts behaving normally again. I know this sounds really weird, but I can't find the source of this problem and it greatly affects the user experience. What could trigger this problem?
I am using node.js version 0.8.24, socket.io 0.9.14 and chrome version 31.0.1650.63 m. I am running on CentOS version 6.5. This behaviour also happens on IE 10 with a different error: "SCRIPT12152: WebSocket Error: Network Error 12152"
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.
I've set up a Ubuntu 10.04 server in my home network. I installed a lamp-server, NodeJs and Socket.io on it. It al seems to work fine but I can not make a connection from my client to the server. I think that I am missing the point of where to store the client files and/or how to the IP adress and port should be put in the code.
I'm using the example from David Walsh (http://davidwalsh.name/websocket). My ip-adress of the server is 192.168.1.113. On the client I store app.js in
/usr/local/bin
That is where node is installed as wel.
Server code
// Require HTTP module (to start server) and Socket.IO
var http = require('http'), io = require('socket.io');
// Start the server at port 8000
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(8000);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function(client){
// Success! Now listen to messages to be received
client.on('message',function(event){
console.log('Received message from client!',event);
});
client.on('disconnect',function(){
clearInterval(interval);
console.log('Server has disconnected');
});
});
When I start the server with Node and enter the adress in a browser (http://192.168.1.113:8000) I see 'Hello Socket Lover!' so I guess this works fine.
I store my client file (client.html) in
/var/www
That is where the home folder of my LAMP server is.
Client.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
<script>
// Create SocketIO instance, connect
var socket = new io.Socket('http://192.168.1.113',{
port: 8000
});
socket.connect();
// Add a connect listener
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('message',function(data) {
console.log('Received a message from the server!',data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
console.log('The client has disconnected!');
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
}
</body>
</html>
Now when I open this file in a browser (http://192.168.1.113/client.html) nothing happens. I see no connection on my Ubuntu server or other logs and there are no messages in the browser.
Ehmm... what am I doing wrong? I've tried for hours, changing all kind of things but still no result.
With the help of pmavik (see comments) my question is answered.
What I didn't know was how to serve the client file properly (index.html). I copied an example from www.socket.io, added the right ip-adress and port and now a connection is made.
The server file (app.js) and the client file (index.html) should be in the directory where Node is installed. The Node-server sends the client file to the browser so there is no need to put the client file in the /var/www directory where the 'normal' files for websites are.
app.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8000);
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);
});
});
index.html
<html>
<head></head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://192.168.1.113:8000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</body>
</html>