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

来源:互联网 发布:用户生命周期算法 编辑:程序博客网 时间:2024/05/18 20:08

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' }

0 0