[英]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. 我是socket.io的新手,正在尝试他们网站上提到的示例。 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. 我使用它很好,但是当我尝试在服务器端使用io.emit并尝试在客户端接收时出现问题。
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. 我在使用ubuntu firefox。 node version: 0.8.7 节点版本: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. 像许多html5功能一样,WebSocket在非Web服务器环境中无法使用。 I mean It won't work if you are accessing your client with the file protocol. 我的意思是,如果您使用文件协议访问客户端,则它将不起作用。 You need to have a http server. 您需要拥有一个http服务器。 What I do to get things done easily, I use python built-in web-server. 为了使事情轻松完成,我使用了python内置的网络服务器。 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). 然后将浏览器指向端口8000(默认)。
I've made a boiler plate socket.io app that you can clone and even push directly to dotCloud.com 我制作了一个样板 socket.io应用程序,您可以克隆它,甚至直接将其推送到dotCloud.com
This is a simple example and could help you to get started with socket.io. 这是一个简单的示例,可以帮助您开始使用socket.io。
Look for examples on the soket.io GitHub page . 在soket.io GitHub页面上查找示例。
You wrote: io.on('connection'
instead io.sockets.on('connection'
您写道: io.on('connection'
而不是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");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.