I am completely new to the socket.io and trying to get my feet wet by starting with examples on their home page. But all that i get in console after execution is this
debug - served static content /socket.io.js
My Server side code is this:
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) {
console.log("connected");
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
})
And my index.html goes like this:
var socket = io.connect('document.location.href');
socket.on('error',function(reason){
// console.error("Error");
});
socket.on('connect', function () {
console.log('connected');
socket.send('hi');
socket.on('message', function (msg) {
// my msg
});
});
</script>
I googled about it and couldn't resolve the issue. I am on ubuntu with firefox.
If i'm not mistaken your error is here:
'document.location.href'
which shall be
document.location.href
I've just complete a simple example app for which I'll be soon writing a tutorial:
https://github.com/dotcloud/socket.io-on-dotcloud
You can grab it (just clone it) and fool around with it to easy how to get started with socket.io with express 3. It is even ready to be push on dotCloud if you whish to share your app.
Related
I have an application under development which uses socket.io to establish Web RTC connections between multiple clients. The application was developed by another developer and I am taking it over for now. One of the things I want to do is move from socket.io v0.9.16 which is being currently used to the most up to date version v1.3.5.
I have looked at the page on migrating from v0.9 to v1.0 and tried changing a few things, however it does not seem to work for me. I am getting the following error in the chrome console:
Failed to load resource: net::ERR_CONNECTION_REFUSED https://143.167.117.93:3000/socket.io/1/?t=1435567474680
indicating that there has been a problem with the socket.io initialisation. The code below shows the way it is being done currently, which works with socket.io v0.9.16.
var protocol = require('https');
var portNo = 3000;
var app = protocol.createServer(options, function (req, res) {
/**
* server serves pages otherwise 404.html
*/
file.serve(req, res, function (err, result) {
if (err) {
console.error('Error serving %s - %s', req.url, err.message);
if (err.status === 404 || err.status === 500) {
file.serveFile(util.format('/%d.html', err.status), err.status, {}, req, res);
} else {
res.writeHead(err.status, err.headers);
res.end();
}
} else {
console.log('serving %s ', req.url);
}
});
}).listen(portNo);
var io = require('socket.io').listen(app, {
log: false,
origins: '*:*'
});
io.set('transports', [
'websocket',
'xhr-polling',
'jsonp-polling'
]);
io.sockets.on('connection', function (socket) {
//Do something
});
If you need any more information to complete this question please let me know. I have limited experience using socket.io and node.js so I apologise if the question is too broad.
Looks like you are not setting correctly socket.io and you are still using some options from socket.io 0.9 version. Try to create a basic example using socket.io migration tutorial, below it is an example of using http node.js library along with socket.io 1.x library.
app.js file:
var protocol = require('http').createServer(handler);
var file = require('fs');
var io = require('socket.io')(protocol);
var portNo = 4040;
protocol.listen(portNo, function() {
console.log('server up and running');
});
function handler(req, res) {
file.readFile(__dirname + '/index.html', function(err, data) {
if (err) {
res.writeHead(500);
return res.send('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function(socket) {
socket.emit('message', 'you just connected dude!');
});
index.html file:
<!doctype html>
<html>
<head>
</head>
<body>
<h1>Hello World</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.js">
</script>
<script>
var socket = io.connect();
socket.on('message', function(message) {
alert(message);
});
</script>
</body>
</html>
I'm experimenting this issue at game.html
GET http://localhost/socket.io/socket.io.js 404 (Not Found) game.html:1
Uncaught ReferenceError: io is not defined game.html:3
My game.html file
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost/game.html');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
And my server.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(5667);
function handler (req, res) {
fs.readFile(__dirname + '/game.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' });
});
It was working fine when I was using index.html instead of game.html
It looks like you're not retrieving game.html from the Node app, because the socket.io.js file seems to be retrieved from an HTTP port running on port 80 whereas your Node app is running on port 5667.
Also, your client-side connection string is incorrect:
var socket = io.connect('http://localhost/game.html');
That also tries to contact a server on port 80 (and I don't know what game.html is doing there).
So try this:
change the client-side connection string to var socket = io.connect();
start your Node app
open http://localhost:5667/ in your browser
And see if that works better.
I have simple socket io code
-- Server
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8080);
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);
});
});
-- Client
<script src="http://192.168.1.100:8080/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://192.168.1.100:8080');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
there is no problem if the client script run on the server machine , but in other machine rather than server there is no problem in getting socket io javascript file , the client send request to server and I can see that the request received by server , but the client do not receive anything and it try to switch transport after 20 sec , none of them work. But as soon as I close server , the client receive the message that sent from server before ...
I use ubunto 12.04 LTS and Google chrome 28 , please help me through this problem
I'm trying to do cross-domain socket.io, but I'm experiencing an issue:
I always get XMLHttpRequest cannot load http://handsonwithnodejs.samarthwiz.c9.io/socket.io/1/?t=1358882710333. Origin https://c9.io is not allowed by Access-Control-Allow-Origin.
Server code:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(process.env.PORT);
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.set('origins', '*:*');
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
On line 19 io.set('origins', '*:*');I tried replacing ':' with '*', 'https://c9.io', 'c9.io','https://c9.io/' and '.', some times when I add something like 'c9.io/'
I get warn 'illegal origin ...' but that is just a cloud9 related issue.
Client code:
<html>
<body>
<script src="https://raw.github.com/LearnBoost/socket.io-client/master/dist/socket.io.js"></script>
<script>
var socket = io.connect('http://handsonwithnodejs.samarthwiz.c9.io');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</body>
</html>
I know that using github to get my script isn't the best idea yet, but I wanted to keep my code clean and the error messages readable(everything in 'socket.io.min.js' is on line 2)
P.S. 1. I know that there are other threads like this but they didn't solve my problem.
2. Please don't reply 'Just host the page on the same server as socket.io' I need it to be cross-domain for a reason.
I think you need to set the Access-Control-Allow-Origin header when you host the client code. Look at https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS for more info about the header.
This header must be set by the client for security reasons.
I'm fairly new to node.js and I've found its quite complicated separating a project into multiple files as the project grows in size. I had one large file before which served as both a file server and a Socket.IO server for a multiplayer HTML5 game. I ideally want to separate the file server, socket.IO logic (reading information from the network and writing it to a buffer with a timestamp, then emitting it to all other players), and game logic.
Using the first example from socket.io to demonstrate my problem, there are two files normally. app.js is the server and index.html is sent to the client.
app.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) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
index.html:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
To separate file server and game server logic I would need the function "handler" defined in one file, I would need the anonymous function used a callback for io.sockets.on() to be in another file, and I would need yet a third file to successfully include both of these files. For now I have tried the following:
start.js:
var fileserver = require('./fileserver.js').start()
, gameserver = require('./gameserver.js').start(fileserver);
fileserver.js:
var app = require('http').createServer(handler),
fs = require('fs');
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);
});
}
module.exports = {
start: function() {
app.listen(80);
return app;
}
}
gameserver:
var io = require('socket.io');
function handler(socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
}
module.exports = {
start: function(fileserver) {
io.listen(fileserver).on('connection', handler);
}
}
This seems to work (the static content is properly served and the console clearly shows a handshake with Socket.IO when the client connects) although no data is ever sent. It's as though socket.emit() and socket.on() are never actually called. I even modified handler() in gameserver.js to add console.log('User connected'); however this is never displayed.
How can I have Socket.IO in one file, a file server in another, and still expect both to operate correctly?
In socket.io 0.8, you should attach events using io.sockets.on('...'), unless you're using namespaces, you seem to be missing the sockets part:
io.listen(fileserver).sockets.on('connection', handler)
It's probably better to avoid chaining it that way (you might want to use the io object later). The way I'm doing this right now:
// sockets.js
var socketio = require('socket.io')
module.exports.listen = function(app){
io = socketio.listen(app)
users = io.of('/users')
users.on('connection', function(socket){
socket.on ...
})
return io
}
Then after creating the server app:
// main.js
var io = require('./lib/sockets').listen(app)
i would do something like this.
app.js
var app = require('http').createServer(handler),
sockets = require('./sockets'),
fs = require('fs');
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);
});
}
sockets.startSocketServer(app);
app.listen(80);
and sockets.js
var socketio = require('socket.io'),
io, clients = {};
module.exports = {
startSocketServer: function (app) {
io = socketio.listen(app);
// configure
io.configure('development', function () {
//io.set('transports', ['websocket', 'xhr-polling']);
//io.enable('log');
});
io.configure('production', function () {
io.enable('browser client minification'); // send minified client
io.enable('browser client etag'); // apply etag caching logic based on version number
io.set('log level', 1); // reduce logging
io.set('transports', [ // enable all transports (optional if you want flashsocket)
'websocket'
, 'flashsocket'
, 'htmlfile'
, 'xhr-polling'
, 'jsonp-polling'
]);
});
//
io.sockets.on('connection', function (socket) {
console.log("new connection: " + socket.id);
socket.on('disconnect', function () {
console.log("device disconnected");
});
socket.on('connect_device', function (data, fn) {
console.log("data from connected device: " + data);
for (var col in data) {
console.log(col + " => " + data[col]);
}
});
});
}
};
i just copy&pasted some of my old code - don't really know what changed in the last versions of socket.io, but this is more about the structure than the actual code.
and i would only use 2 files for your purposes, not 3.
when you think about splitting it up further, maybe one other file for different routes ...
hope this helps.
I have had a crack at this as well and I am fairly happy with the result. Check out https://github.com/hackify/hackify-server for source code.
I've another solution. You can use require.js creating a module and pass "app" as an argument. Within the module you can start socket.io and organize your sockets.
app.js:
var requirejs = require('requirejs');
requirejs.config({
baseUrl: './',
nodeRequire: require
});
requirejs(['sockets'], function(sockets) {
var app = require('http').createServer()
, fs = require('fs')
, io = sockets(app);
// do something
// add more sockets here using "io" resource
});
In your socket.js module you can do something like this:
define(['socket.io'], function(socket){
return function(app){
var server = app.listen(3000)
, io = socket.listen(server);
io.sockets.on('connection', function (socket) {
console.log('connected to socket');
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
// more more more
});
return io;
}
});
I hope help you with my contribution.