您的位置:首页 > Web前端 > Node.js

nodejs之socket.io模块——实现了websocket协议

2015-08-07 16:58 417 查看
Nodejs实现websocket的4种方式:socket.io、WebSocket-Node、faye-websocket-node、node-websocket-server,这里主要使用的是socket.io

1、服务端:

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);
    });
});


2、客户端:

1)websocket是html5标准,浏览器内部已经支持了,其编程接口大致有connect、close、open、send几个接口,如果要使用浏览器原生的方式编写websocket,比较繁琐,所以可以下载一个客户端库方便编程,这里使用的是socket.io客户端库,点击打开链接

2)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="https://cdn.socket.io/socket.io-1.3.5.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>


3、测试:

启动服务端nodejs代码:node server.js

在浏览器输入 http://localhost:8080/index.html
浏览器打印出: world

命令行打印出:{ my: 'data' }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: