1

我是 socket.io 的新手,我正在尝试他们网站上提到的示例。我很好,但是当我尝试在服务器端使用 io.emit 并尝试在客户端接收时会出现问题。

这是我的服务器代码

var io=require("socket.io").listen(8888);
io.set('log level',1);
io.on('connection',function(socket){ 
socket.emit('hi');
console.log("Connected");
});

还有我客户的代码

<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>

问题是我在控制台中没有看到“收到”消息!答案可能微不足道,但我尝试过尝试但每次都失败了。请指导....

我在ubuntu firefox上。节点版本:0.8.7

4

2 回答 2

1

所以你应该在服务端有这个:

var io = require('socket.io').listen(88888);
io.set('log level',1);
io.sockets.on('connection', function (socket) {
  socket.emit('hi);
  console.log("Connected");
  });
});

你应该在客户端有这个:

<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.

于 2012-08-25T11:21:27.490 回答
0

在soket.io GitHub 页面上查找示例。

你写道:io.on('connection'相反io.sockets.on('connection'

此代码应该可以正常工作:

var io = require('socket.io').listen(8888);
io.set('log level', 1);
io.sockets.on('connection', function(socket){ 
    socket.emit('hi');
    console.log("Connected");
});
于 2012-08-25T11:20:00.693 回答