我正在研究一个简单的Node.js双向客户端\服务器通信通道,我正在尝试在服务器上使用socket.io,在客户端上使用socket.io- client.
我已经在下面插入了代码,因为你会看到它是非常基本的东西,我在我的本地机器上运行 - 以最大限度地降低复杂性.
我看到的行为是:
我期望的是服务器记录'客户端就绪!' 消息,然后是内容('Ready received').
我甚至使用WireShark来嗅探线路,看起来客户端正在按照设计发出消息 - 但是服务器上的回调没有触发.
我正在运行node v0.8.4 with express v3.1.0,socket.io v0.9.13和socket.io-client v0.9.11(全部通过npm安装).
这是服务器代码......
var http = require('http'),
express = require('express'),
app = express(),
server = http.createServer(app);
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
server.listen(8080);
console.log("Server started");
var io = require('socket.io').listen(server);
io.sockets
.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' }) ;
})
.on('comms', function(content) {
console.log('Client is ready!');
console.log(content);
});
Run Code Online (Sandbox Code Playgroud)
这是客户端代码......
var clientio = require('socket.io-client');
var socket = new clientio.connect('http://localhost', { port: 8080 });
socket
.on('server ready', function(data){
console.log('Server is ready!');
socket.emit('comms', 'Ready received');
})
.on('connect-error', function(error) {
console.log('Connection Error\n' + error);
})
.on('error', function(error) {
console.log('Socket Error\n' + error);
})
Run Code Online (Sandbox Code Playgroud)
socket.io和socket.io-client的文档和示例有点混淆(要慈善),它们似乎是一个移动的目标...但从我所知,我认为这应该工作.
我希望有人能就我出错的地方给我建议吗?
在你的服务器中有这样的代码:
io.sockets
.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' }) ;
})
.on('comms', function(content) {
console.log('Client is ready!');
console.log(content);
});
Run Code Online (Sandbox Code Playgroud)
你应该做的是这样的:
io.sockets.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' });
socket.on('comm', function(content){
console.log('Client is ready!');
console.log(content);
});
});
Run Code Online (Sandbox Code Playgroud)