Gas*_*ton 12 websocket node.js express socket.io
问题 socket.io不工作
细节
express [folder]; cd [folder]; npm install;
npm install socket.io
建立
客户
var socket = io.connect('http://example.com:3000');
socket.on('connect', function() {
console.log('connected');
});
socket.on('message', function(msg){
console.log(msg);
});
socket.on('disconnect', function() {
console.log('disconnected');
});
socket.on('error', function (e) {
console.log('System', e ? e : 'A unknown error occurred');
});
Run Code Online (Sandbox Code Playgroud)
服务器
[...]
app.listen(3000);
// socket.io setup
var socket = require('socket.io').listen(app);
// socket.io connection establishment
socket.on('connection', function (client) {
client.send("hello");
console.log("hello", client);
});
Run Code Online (Sandbox Code Playgroud)
为什么连接事件从未被触发?
Ric*_*asi 12
花了一段时间才注意到... connection
事件已经开始了io.sockets
.在你的代码中,这将是
socket.sockets.on('connection', function (client) {
client.send("hello")
console.log("hello", client)
})
Run Code Online (Sandbox Code Playgroud)
您应该使用io
而不是socket
var名称来避免这种混淆.
归档时间: |
|
查看次数: |
40926 次 |
最近记录: |