服务端和客户端都需要引入:socket.io

socket.io的js下载:官网->blog去下载socket.io.js

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>

socket.io的安装,cmd执行命令:npm install socket.io 

socket.io之五

服务端代码:

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

app.listen(8005);

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

客户端代码:


<html>
  <head>
    <title>websocket</title>
    <script src="socket.io.js"></script>
  </head>
  <body>
  <script>
    var socket=io('ws://localhost:8005');
    socket.on('news',function(data){
        console.log(data);
        socket.emit('my other event',{my:'data'});
    })
  </script>
  </body>
</html>

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-02
  • 2021-12-29
  • 2021-11-04
  • 2021-07-06
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-30
  • 2021-08-17
  • 2021-11-13
相关资源
相似解决方案