这个是我用socket.io写的一个小项目的一段代码,和net中的socket是一样道理的,希望对你有帮助
var socketConns = {};//保存连接实例
soceketIO.setMaxListeners(0);//不限制监听最大数
soceketIO.sockets.on("connection",function(socket)
{
socket.setMaxListeners(0);//不限制监听最大数
socket.volatile.emit("who",{msg:""});
var clientSocket=new Object();
socket.on("verify",function(data)
{
clientSocket.soct=socket;
clientSocket.nickname=data.nickname;
clientSocket.uid=data.uid;
clientSocket.username=data.username;
//var socID=socket.id;
socketConns[socket.id]=clientSocket;
for(var socId in socketConns) //广播效果
{
if(socId===socket.id)
{ var userlist="[";
for(var socId in socketConns)
{
var oneuser="{nickname:"+"\""+socketConns[socId].nickname+"\""+",username:"+"\""+socketConns[socId].username+"\""+",uid:"+"\""+socketConns[socId].uid+"\""+"},";
userlist=userlist+oneuser;
}
userlist=userlist.substr(0,userlist.length-1);
userlist=userlist+"]";
socketConns[socId].soct.volatile.emit("userlist",{userlist:userlist});//发送聊天室列表
}
else
{
socketConns[socId].soct.volatile.emit("new user",{msg:data.nickname+"加入聊天室!",nickname:socketConns[socket.id].nickname,uid:socketConns[socket.id].uid,username:socketConns[socket.id].username}); //volatile指可丢弃的数据
}
}
hand_mysql.updateUserOnline(data.username,1);//设置数据库用户在线
});
socket.on("disconnect", function () {
var leaveName=socketConns[socket.id].nickname;
var leaveNameUid=socketConns[socket.id].uid;
var leaveUsername=socketConns[socket.id].username;
delete socketConns[socket.id];
for(var socId in socketConns) {
socketConns[socId].soct.volatile.emit("userdisconnect", {msg:leaveName+"已经离开聊天室!",uid:leaveNameUid});
}
hand_mysql.updateUserOnline(leaveUsername,0);
});
socket.on("msg",function(data)
{
console.log("Get a msg from client...");
for(var socId in socketConns) //广播效果
{
if(socId!=socket.id)
socketConns[socId].soct.volatile.emit("user message",data);
}
//socket.broadcast.emit("user message",data); //
});
});
但是,net模块没有类似
socket.broadcast.emit("user message",data);
这些广播用的方法,原来socket.io我也用过,但是浏览器不兼容,改成flash了,我知道存数组的方法,但是就是不知道广播的方法
var XML =
'<cross-domain-policy>' + '<allow-access-from domain="*" to-ports="*" />' + '</cross-domain-policy>\0’
var net = require(‘net’), http = require(“http”), fs = require(“fs”), path = require(“path”), url = require(“url”), ctrl = require(“./ctrl”);
var server = net.createServer(function(socket){
socket.on(‘data’, function(data) {
if(data.toString()==’<policy-file-request/>\0’){
socket.end(XML);
console.log(‘客户端flash已与服务器建立连接,可以正常传输数据了!’);
}else{
console.log(data.toString());
socket.write(data.toString());
}
});
socket.on('error',function(){
console.log('程序出现异常!');
});
}); server.listen(3944, ‘192.168.1.122’); console.log(‘服务端已开启…’);