websocket示例程序:没有得到回调

时间:2015-03-18 10:59:27

标签: javascript node.js websocket

我创建了一个服务器和客户端。这是完美的。但我必须用回调来实现它。哪个未定义。

我的代码:
服务器端代码

var net = require('net');
var HOST = '127.0.0.1';
var PORT = 6969;
net.createServer(function(socket) {    
    console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
    socket.on('data', function(data, callback) { 
      console.log('Data from client :' + data + '\n');
      return callback('error', 'message');
    });
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);

客户端代码

var net = require('net');
var HOST = '127.0.0.1';
var PORT = 6969;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
});

client.write('I am Chuck Norris!', function(error, response){
  console.log(error, response);
});

我在服务器端收到此错误

/web/ws/server.js:10
      return callback('error', 'message');
             ^
TypeError: undefined is not a function
    at Socket.<anonymous> (/web/ws/server.js:10:14)
    at Socket.emit (events.js:95:17)
    at Socket.<anonymous> (_stream_readable.js:764:14)
    at Socket.emit (events.js:92:17)
    at emitReadable_ (_stream_readable.js:426:10)
    at emitReadable (_stream_readable.js:422:5)
    at readableAddChunk (_stream_readable.js:165:9)
    at Socket.Readable.push (_stream_readable.js:127:10)
    at TCP.onread (net.js:528:21)

客户端结果

CONNECTED TO: 127.0.0.1:6969
undefined undefined

**我尝试过使用socket.io工作正常 **但标准是“净”包

我错过了什么吗?可以在这里使用回调吗?请让我明白。感谢

1 个答案:

答案 0 :(得分:0)

data库中的net事件处理程序没有回调函数。 e.g:

socket.on('data', function (chunk) {

});

如果您想捕获所有数据消耗的事件,您可以使用:

socket.on('end', function () {

});

您的代码如下所示:

var chunks = [];

socket.on('data', function (chunk) {
    chunks.push(data);
});

socket.on('end', function (chunk) {
    chunks = chunks.join('');
});