Node.js 基础篇(十六):Socket 编程(二):基于 WebSocket 模块的 Socket 编程

在这里插入图片描述

npm i ws

ServerSocket.js

const WebSocket = require('ws')

const wss = new WebSocket.WebSocketServer({
    
     port: 9527 });

wss.on('connection', (ws) => {
    
    
  ws.on('open', () => {
    
    
    console.log('connected');
    ws.send(Date.now());
  });

  ws.on('message', (data, isBinary) => {
    
    
    wss.clients.forEach(function each(client) {
    
    
      if (client.readyState === WebSocket.OPEN) {
    
    
        client.send(data.toString(), {
    
     isBinary });
      }
    });
  });

  ws.on('close', () => {
    
    
    console.log('disconnected');
  });
});

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>WebSocket</title>
  <script src="./WsClient.js" charset="utf-8"></script>
</head>
<body>
<h1>交流区</h1>
<div id="content" name="name" style="overflow-y: scroll; width: 400px; height: 300px; border: solid 1px #000"></div>
<br />
<div>
  <input type="text" id="msg" style="width: 200px;">
  <button id="submit">发送</button>
</div>
<script>
  document.querySelector('#submit')
    .addEventListener('click', function () {
     
     
      const msgDom = document.getElementById('msg')
      ws.send(msgDom.value) // 核心代码,将表单里的数据提交给server端
      msgDom.value = ''
    }, false)
</script>
</body>
</html>

WsClient.js

const ws = new WebSocket('ws://localhost:9527/')

ws.onopen = () => {
    
    
  ws.send('大家好!')
}

ws.onmessage = (msg) => {
    
    
  const content = document.getElementById('content')
  content.innerHTML += `${
      
      msg.data} <br/>`
}

ws.onerror = (err) => {
    
    
  console.log(err);
}

ws.onclose = () => {
    
    
  console.log('closed~');
}

猜你喜欢

转载自blog.csdn.net/qq_41887214/article/details/123655319
今日推荐