I'm having trouble connecting to socket.io. With the code below, I keep getting an 'io is not defined' error on my browser console. Anyone have any idea what I'm doing wrong here? I've been poking around stackoverflow for hours, but no solution seems to work...
server side:
,db = require("../../lib/db")
,config = require("../../config")
,app = require("../index")
,io = require('socket.io')(app);
;
io.on('connection', function (socket) {
console.log('connected')
});
exports.render = function(req, res){
console.log(io)
res.render("vitron", {});
}
client side:
<!doctype html>
<html>
<head>
<title>Sockets</title>
<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>
</head>
<body>
</body>
</html>
You apparently don't have the right server-side initialization so that your server will automatically serve the /socket.io/socket.io.js file.
There are many ways to do this, but the simplest way that is documented in the socket.io documentation is to use some built-in middleware that will have the socket.io server-side library automatically intercept the request for the /socket.io/socket.io.js file and serve up the script file.
The socket.io documentation shows exactly how to do this when using express with node. If you aren't using express, then you can do it with your own middleware. Or, if you're just using plain node, you will have to either handle that route yourself or just put the /socket.io/socket.io.js file in a known location that it can be requested directly from. You can even link to it on a CDN if you want, but there is an advantage to using the built-in scheme because when/if you upgrade the socket.io library on the server, it will automatically contain a matching client-side library which is kind of nice.
I don't know exactly what your overall setup is, but here's my socket.io initialization with express 4.
var express = require('express');
var app = express();
var server = app.listen(8081, function() {
console.log(new Date().toISOString() + ": server started on port 8081");
});
var io = require('socket.io').listen(server);
Related
I have a basic node express/socket example app from the socket.io official website (linked pasted below) and i noticed that when a user connected, the 'connection' even just kept firing over and over again.
So i found a post (Socket IO chat repeating user connected) saying that there is a bug in socket.io 2.x.x and when i reverted to socket.io 1.3.7 this issue did stop, is this a confirmed bug, and we should roll back to a 1.x.x version? Or is there a new way of using socket.io that doesn't reflect on the current documentation?
My server code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
My Client side code:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
My server terminal output (which just repeats forever):
a user connected
a user connected
a user connected
...
Socket.io official example:
https://socket.io/get-started/chat/
Since socket.io released version 2.x, there appears to be an issue that causes an infinitely recurring connect, disconnect, connect, disconnect and so on forever if you have mismatched versions of socket.io code on client and server.
This can be further exacerbated by client-side caching which can get the browser client stuck on an older version sometimes.
The usual fix is to make sure you're getting the socket.io client with /socket.io/socket.io.js because then the socket.io server sends the client version that matches it exactly. But, you appear to already being doing that, so I'd guess that you have some sort of browser caching problem. You can clear the browser cache manually to see if this is the issue.
Use this for the server:
var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('node_modules')); // serve static files
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
And this in the HTML:
<!DOCTYPE html>
<html lang="en">
<body>
<script src="socket.io-client/dist/socket.io.js"></script>
<script>
var socket = io();
</script>
</body>
</html>
The bug might be with the <script src="/socket.io/socket.io.js"></script> tag that Socket IO provides.
when I run socket.io locally let say http://localhost:8000/ this does not pick all the folders for css and js. here's my structure:
<head>
<script type="text/javascript" src="js/main.js"></script>
<link rel="stylesheet" href="css/main.css">
<script src="socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<script>
var socket = io.connect('http://localhost:8000');
$('.box').click(function(){
var content = $(this).attr('id');
//console.log(content);
socket.emit('click',content);
});
socket.on('test', function(content){
$(".box").css({"background":"grey"});
$(".one,.two,.three,.four").hide();
$("#"+content).css({"background":"red"});
$("."+content).fadeIn();
//$('.box').css({"background":"grey"});
});
</script>
server.js :
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs');
// creating the server ( localhost:8000 )
app.listen(8000);
// on server started we can load our client.html page
function handler(req, res) {
fs.readFile(__dirname + '/client.html', function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client.html');
}
res.writeHead(200);
res.end(data);
});
io.sockets.on('connection', function(socket){
socket.on('click', function(data){
io.sockets.emit('test',data);
});
});
console is throwing this below that it cannot be found:
"http://localhost:8000/css/normalize.css".
"http://localhost:8000/css/main.css".
Can someone help please?
second question:
I'm very new to this, so not sure if this does not sound stupid. But I would like to run this from actual directory let say: http://localhost/test/test2:8000 instead of http://localhost:8000/
You seem to be misunderstanding the role of Socket.io. This javascript library handles real-time communication between the clients and your server. In your code, you don't use Socket.io at all: you don't define any connection handler nor do you emit any event.
What you should do instead is modify the code of your HTTP server to serve the files. In your example, you have to edit the handler function that handles the incoming requests. Please look at the documentation for the HTTP module. Your app is an http.Server object. Your handler function, per the documentation, is:
The requestListener is a function which is automatically added to the 'request' event.
which handles an http.IncomingMessage. You should then look at the url property, which contains the URL that the client requested, in order to serve the correct file. In your example, you always serve the same file: client.html.
To conclude, I'd suggest that you should have a look at some javascript libraries that ease the creation of a webserver, for instance Express, or Hapi. This will be easier your you than to handle each request by hand.
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.
Im fairly new to NodeJS(using c9.io) and have this sick obsession with it lately.
I would like to know while using NodeJS. Is it possible to stream the contents of a basic html page, not large, and not special to lets say 10 concurrent users. However if there is a change to that html page the users will instantly see the changes. This can be based on whatever event but basically on the file contents being updated. Im really hoping to create some simple prototype to impress the boss and do it with NodeJS with hopes to get ride of our current out-dated use of setInterval ajax posts. puke
What is the name of this process because i keep hearing different names.
Is it Possible?
What else would i need in addition to NodeJS
Where is a good starting point?
Thanks
Ok, here is a really simple example.
A textarea synchronizes with login members.
Please install http, socket.io and express(ver3).
sudo npm install http, socket.io, express
And create a javascript file.
server.js
var app = require('express')(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
member_sockets = {},
key;
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
var user_id = socket.id;
member_sockets[user_id] = socket;
console.log("[login]-->", user_id);
socket.on('txt_change', function (data) {
for (key in member_sockets) {
if (key != user_id) {
member_sockets[key].emit("txt_change", data);
}
};
});
socket.on('disconnect', function (socket) {
console.log("[logout]-->", user_id);
delete member_sockets[user_id];
});
});
In the same directory, you also create an index.html file.
index.html
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('txt_change', function (data) {
console.log(data);
$("#txt").val(data.txt);
});
$(document).ready(function(){
$("#txt").keyup(function(){
socket.emit('txt_change', { "txt" : $(this).val() });
});
});
</script>
</head>
<body>
<textarea id="txt" style="width:200px;height:100px"></textarea>
</body>
</html>
Then run the server with this command:
sudo node server.js
So the code should work like this picture:
Did you check socket.io? You can create the push server easily using socket.io module.
http://socket.io/
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");
});