转 nodejs socket.io初探

1、安装socket.io

npm install socket.io

2、创建服务端代码server.js

复制代码
var app = require('http').createServer(handler), 
    io = require('socket.io').listen(app), 
    fs = require('fs')

app.listen(8080);
io.set('log level', 1);//将socket.io中的debug信息关闭

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',function (err, data) {  
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }    
    res.writeHead(200, {'Content-Type': 'text/html'});    
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
      console.log(data);
    });
});
复制代码

3、创建客户端代码 index.html

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Ssocket</title>
    <script type="text/javascript" src="http://localhost:8080/socket.io/socket.io.js"></script>     
</head>

<body>
    <script type="text/javascript">
      var socket = io.connect('http://localhost:8080');     
      socket.on('news', function (data) {    
        alert(data.hello);
        socket.emit('my other event', { my: 'data' });
      });
    </script>
    
</body>
</html>
复制代码

4、执行结果

启动服务端:

node  server.js

在浏览器输入 http://localhost:8080/index.html

浏览器打印出: world

命令行打印出:{ my: 'data' }

5、更多资料参见官方网站 http://socket.io/#how-to-use

6、服务端向指定客户端发送消息

思路是客户端与服务端建立连接的时候,服务端保存客户端的信息,做一个socketMap, 在socketMap中取出需要发送消息的客户端,向该客户端发送消息

做一个模拟的简单例子,这里用的是数组:

复制代码
var sockets = [];
var i = 1;
io.sockets.on('connection', function (socket) {
    sockets[i] = socket;
    i++;
    socket = sockets[1];  //这里指定向第一个客户发送消息
    console.log(i);
    
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
      console.log(data);
    });
});
复制代码
原文地址:https://www.cnblogs.com/qilinge/p/5304777.html