function handler(req,res){
//__dirname返回该文件所在的当前目录。调用readFile方法进行文件读取
fs.readFile(__dirname+'/index.html',function(err,data){
if(err){
res.writeHead(500);
return res.end('error ');
}
res.writeHead(200);
res.end(data);
});
}
//以上步骤成功在8888端口渲染出相应的html界面
//conn是对应的connection的实例
var server = ws.createServer(function(conn){
console.log('new conneciton');
//监听text事件,每当收到文本时触发
conn.on("text",function(str){
broadcast(server,str);
});
//当任何一端关闭连接时触发,这里就是在控制台输出connection closed
conn.on("close",function(code,reason){
console.log('connection closed');
})
}).listen(5000);
//注意这里的listen监听是刚才开通的那个服务器的端口,客户端将消息发送到这里处理
function broadcast(server, msg) {
//server.connections是一个数组,包含所有连接进来的客户端
server.connections.forEach(function (conn) {
//connection.sendText方法可以发送指定的内容到客户端,传入一个字符串
//这里为遍历每一个客户端为其发送内容
conn.sendText(msg);
})
}
以上就是本文
的全部内容,希望对大家的学习有所帮助,也希望大家多多支持软件开发网。









