学习 NodeJS 第八天:Socket 通讯实例

2020-06-17 06:57:36易采站长站整理

<script>
var upandrunning = io.connect('http://localhost:8080/upandrunning');
var weather = io.connect('http://localhost:8080/weather');
upandrunning.on('message', function(data){
document.write('<br /><br />Node: Up and Running Update<br />');
document.write(data);
});
weather.on('message', function(data){
document.write('<br /><br />Weather Update<br />');
document.write(data);
});
</script>
</body>
</html>

服务端代码:


var sockFile = fs.readFileSync('socket.html');

server = http.createServer();
server.on('request', function(req, res){
res.writeHead(200, {'content-type': 'text/html'});
res.end(sockFile);
});

server.listen(8080);

var socket = io.listen(server);

socket.of('/upandrunning')
.on('connection', function(client){
console.log('Client connected to Up and Running namespace.');
client.send("Welcome to 'Up and Running'");
});

socket.of('/weather')
.on('connection', function(client){
console.log('Client connected to Weather namespace.');
client.send("Welcome to 'Weather Updates'");
});

 如上代码,我们可以划分多个命名空间,分别是 upandrunning 和 weather。

关于 Express 中使用 Soclet.io,可以参考《Node:Up and Ruuning》一书的 7.2.2 小节。

今晚时间的关系,涉及 Socket.io 许多方面还没有谈,容小弟我日后再了解。