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");
});
Related
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);
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>
when i try to communicate with my socket io, the connection is established and the websocket writing is taking place, but the hearbeat is not getting emitted on the server ..so im not receiving anything on the client side. but when i disconnect and connect the server again, the old written message is getting emitted. please help me through this. thank you
I have tried with different port numbers, but its not working.
app.js (Server):
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log("Connected");
});
});
index.html (Client)
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
Socket.io might work unstable because of firewall or antivirus. This is actually a problem of WebSockets.
To solve this you may try to exclude WebSockets from the transports between client and server and specify on server side just XHR long polling and JSONP (as these two are the most stable):
io.set('transports', ['xhr-polling', 'jsonp-polling']);
I would also recommend to take a look at Engine.io. This framework is written by Socket.io author as the alternative, which works more stable.
The trick is following:
While Socket.io tries to connect via WebSockets first (when this attempt is fail, user will have to wait about 10 sec to switch to another transport), Engine.io tries to connect via XHR (which works in 100% cases), and meanwhile tries WebSocket connection, and if success - switching to WebSockets occurs.
Edit: Socket.io version 1.0+ is built on the top of Engine.io, so it has now all the benefits described above.
I am new to Node.js and Socket.io. I am supposed to connect through a server using Android but I want to test first if I can connect to Node/Socket server using a browser like for example typing http:server:8000/?v=1&username=test&password=test. Is this possible?
I think the tutorial, on socket.io webpage (http://socket.io/), is a good start for you.
In a nutshell, you create a server that will listen for events like this piece of code:
// Load socket.io module and start listening on port 8000
var io = require('socket.io').listen(8000);
io.sockets.on('connection', function (socket) {
// This is trigerred on a login event sent from the client
socket.on('login', function(data) {
// Do what you want with your data here
// Then emit a response
socket.emit('login-response', {data: 'ok'});
});
});
And on the client side you create this:
<!-- Load the socket.io library -->
<script src="/socket.io/socket.io.js"></script>
<script>
// Connect to your server
var socket = io.connect('http://localhost');
// Emit your login event
socket.emit('login', {username: 'test', password: 'test'});
// When you retrieve the login response
socket.on('login-response', function (data) {
console.log(data);
});
</script>
I'm trying to set up a simple NodeJS - socket.io web application.
I have installed NodeJS and Socket.io on my Raspberry pi and I can start the server script without any problems.
I have downloaded the client socket.io, which I'm loading in the frontend script.
My problem is, whenever I try to connect to my server my browser gives me these errors.
Error: failed to require "socket.io" from "root"
...plete}}});require.register("learnboost-engine.io-client/lib/transports/websocket...
socket.io.js (linje 1)
ReferenceError: io is not defined
var socket = io.connect('http://192.168.0.105:8888');
Here is the server script.
var io = require('socket.io').listen(8888);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
console.log('Running fine');
Here is my frontend script.
<!--<script src="localhost:8080/socket.io/socket.io.js"></script>-->
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://192.168.0.105:8888');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
My Raspberry pi is hosting the nodejs - socket.io, and the website is hosted on my main computer with Wampserver.
I really hope someone can help me :) Thanks in advance.
Socket.io.js is hosted by NodeJS server, so you should connect to
<script src="192.168.0.105:8888/socket.io/socket.io.js"></script>
And
http://192.168.0.105:8888 is wrong, http means that you want to use port 80
.You should use 192.168.0.105:8888 instead.
it says here that
var socket = io()
connects to the host server by default, which means you don't have to put anything in there
http://socket.io/get-started/chat/