潍坊网站建设:NodeJS怎么实现WebSocket功能

2018.04.16 WebSocket功能,潍坊网站建设

188

潍坊网站建设:NodeJS怎么实现WebSocket功能


  这次潍坊网站建设给大家带来NodeJS怎么实现WebSocket功能,NodeJS实现WebSocket功能的注意事项有哪些,下面就是实战案例,一起来看一下。

 

  我们基于express和socket.io开发,首先我们需要安装以下包

 

  npm install--save express

 

  npm install--save socket.io

 

  服务器端代码:

 

  var app=require('express')();

 

  var http=require('http').Server(app);

 

  var io=require('socket.io')(http);

 

  app.get('/',function(req,res){

 

  res.send('<h1>Welcome Realtime Server</h1>');

 

  });

 


潍坊网站建设


  io.on('connection',function(socket){

 

  console.log('a user connected');

 

  socket.on("disconnect",function(){

 

  console.log("a user go out");

 

  });

 

  socket.on("message",function(obj){

 

  io.emit("message",obj);

 

  });

 

  });

 

  http.listen(3000,function(){

 

  console.log('listening on*:3000');

 

  });



潍坊网站建设公司

 

  客户端代码

 

  <!DOCTYPE html>

 

  <html>

 

  <head>

 

  <meta charset="UTF-8">

 

  <title>Document</title>

 

  <script src=http://www.php.cn/"http://127.0.0.1:3000/socket.io/socket.io.js"></script>

 

  </head>

 

  <body>

 

  <ul id="message"></ul>

 

  <script>

 

  socket=io.connect('ws://127.0.0.1:3000');

 

  socket.emit("message",{"name":navigator.userAgent,"msg":"hello world"});

 

  socket.on("message",function(obj){

 

  console.log(obj);



潍坊建设网站

 

  });

 

  </script>

 

  </body>

 

  </html>

 

  一个控制台版的聊天室做好了(^o^)/~  

 

  转载请注明:潍坊网站建设:http://www.mfdream.com/newsshow/213.html


关键词

最新案例

联系电话 400-6065-301

留言