如何在socket中传递参数

我需要在socket中传递参数,并使用方法emit
服务器端:

 var http=require('http'); var numero_giocatori=0; var express = require('express'); var app = express(); var net = require('net'); var client = new net.Socket(); var vettore_clienti=[]; var chatServer = net.createServer(); chatServer.on('connection', function(client) { numero_giocatori=numero_giocatori+1; vettore_clienti.push(client); if(numero_giocatori===2){ console.log("IScritto "+numero_giocatori); for(var i=0;i<vettore_clienti.length;i++){ vettore_clienti[i].emit('vettore_clienti',vettore_clienti); } } }); chatServer.listen(8000,'127.0.0.1'); 

但是我不知道如何读取我首先通过emit方法传递的值。
客户端:

 var net = require('net'); var client = new net.Socket(); client.connect(8000, '127.0.0.1', function() { }); client.on('data', function(data) { console.log(data); }); 

节点的TCP套接字意味着是通用的(另一端不一定是一个节点程序),并没有规定如何格式化消息的任何标准。 换句话说:您可以自由创build自己的邮件编码。

或者你可以简单地使用JSON(如果你不关心这个创build的开销,那么和一个更适合你的特定用例的编码相比):

服务器

 var http=require('http'); var numero_giocatori=0; var express = require('express'); var app = express(); var net = require('net'); var client = new net.Socket(); var vettore_clienti=[]; var chatServer = net.createServer(); function sendMessage(client, messageType) { var message = {type: messageType, data: [].slice.call(arguments, 2)}; client.write(JSON.stringify(message)); // Sending a string implicitly converts it into a buffer using utf-8 } chatServer.on('connection', function(client) { console.log('Got connection', client); numero_giocatori=numero_giocatori+1; vettore_clienti.push(client); if(numero_giocatori===2){ console.log("IScritto "+numero_giocatori); for(var i=0;i<vettore_clienti.length;i++){ sendMessage(vettore_clienti[i], 'welcome', "You are client number", i+1, 'of', vettore_clienti.length); } } }); chatServer.listen(8000,'127.0.0.1'); 

客户

 var net = require('net'); var client = new net.Socket(); client.connect(8000, '127.0.0.1', function() { console.log('Connected'); }); client.on('data', function(data) { var message = JSON.parse(data.toString()); // calling toString() with no arguments assumes the buffer is in utf-8 var messageType = message.type; var data = message.data; console.log.apply(console, data); }); 

请注意,通过这种方式,您仅限于发送实际上可以用JSON表示的内容。 这不包括函数,像NaNInfinity这样的值。 发送一个完整的函数和stream的客户端arrays,就像你在示例代码中尝试的那样,将无法工作。

我不知道如果node.jsnetworking套接字库有一个发射方法。

文档build议通过套接字write方法完成通过套接字发送数据。


socket.io将允许您创buildwebsocket连接,并发出和监听任意事件:

http://socket.io/docs/server-api/#server#emit