nodejs+websocket实现即时通讯

环境要求:
Node.js环境安装
npm(Node.js的包管理器)
步骤:
安装Node.js:如果你还没有安装Node.js,请从Node.js官网下载并安装。

创建项目:创建一个新的目录作为项目文件夹,并在该目录下初始化一个新的Node.js项目。

mkdir my-websocket-server
cd my-websocket-server
npm init -y
3. 安装WebSocket库:使用npm来安装ws库。

npm install ws
4. 创建WebSocket服务端:在项目目录中创建一个名为server.js的文件,并添加以下代码:

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
    ws.send(`Hello, you said: ${message}`);
  });
});

5.客户端:

<!DOCTYPE html>

<htmllang="en">

<head>

  <metacharset="UTF-8">

  <metaname="viewport"content="width=device-width, initial-scale=1.0">

  <title>WebSocket Demo</title>

</head>

<body>

  <input type="text"id="messageInput"placeholder="Enter message...">

  <button onclick="sendMessage()">Send</button>

  <ul id="messageList"></ul>
</body>
<script> 
  const socket
= new WebSocket('ws://localhost:8080');
  socket.onopen
= function(event) { console.log('Connection opened'); };
  socket.onmessage
= function(event) {
    const messageList
= document.getElementById('messageList');
    const li
= document.createElement('li');
    li.textContent
= event.data;
    messageList.appendChild(li);
  };
function sendMessage() {
  const messageInput
= document.getElementById('messageInput');
  socket.send(messageInput.value);
  messageInput.value
= '';
}
</script>
</html>

 

 

 

 

 

引用:

https://blog.csdn.net/weixin_49822873/article/details/137334867

https://mp.weixin.qq.com/s/7gD_VPqONnG0oM4LAE8mtQ

posted @ 2024-05-13 15:27  陆远0913  阅读(14)  评论(0)    收藏  举报