21xrx.com
2024-09-20 01:05:39 Friday
登录
文章检索 我的文章 写文章
Node.js实现一对一聊天功能
2023-06-26 02:52:56 深夜i     --     --
Node js 实现 一对一聊天 功能

Node.js是一种运行在服务端的JavaScript编程语言,它的优点是高效、轻量级、事件驱动、非阻塞I/O模型。在实际应用开发过程中,Node.js可以用于构建服务器端应用、实现实时通信、提供API接口等。

本文将从实现一对一聊天功能的角度来介绍Node.js的应用。一对一聊天是指两个用户之间的即时通信,基本思路是前端页面通过websocket与后端节点连接通信,后端节点负责转发用户的聊天信息。

首先,我们需要安装一个websocket库package,该库可以通过npm进行全局安装,命令行输入


npm install websocket -g

我们可以使用这个库快速构建一个聊天服务器端,代码如下


const WebsocketServer = require('websocket').server;

const http = require('http');

const server = http.createServer((request, response) =>

  // process HTTP request. Since we're writing just WebSockets

  //server we don't have to implement anything.

);

server.listen(8000, function() { });

// create the server

wsServer = new WebsocketServer(

  httpServer: server

);

// WebSocket server

wsServer.on('request', function(request) {

  const connection = request.accept(null, request.origin);

  console.log((new Date()) + ' Connection accepted.');

  connection.on('message', function(message) {

    if (message.type === 'utf8') {

      console.log('Received Message: ' + message.utf8Data);

      // process WebSocket message

      connection.sendUTF(message.utf8Data);

    }

  });

  connection.on('close', function(reasonCode, description) {

    console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');

  });

});

这段代码中,我们首先创建了一个http对象,并监听端口8000。然后创建websocket服务器,当有一个请求连接该服务器时,就会创建一个新的websocket连接,并能够接收和发送消息。

下面是前端页面的代码,我们可以在html文件中引用官方提供的javascript库来实现websocket通讯,代码如下:


<!DOCTYPE html>

<html>

  <head>

    <meta charset="UTF-8" />

    <title>Websocket chat application</title>

    <style>

      #output

        width: 500px;

        height: 300px;

        margin: 10px auto;

        padding: 10px;

        border: 1px solid #ddd;

      

    </style>

  </head>

  <body>

    <div id="output"></div>

    <input type="text" id="input" />

    <button type="button" id="send">Send</button>

    <script>

      const output = document.getElementById('output');

      const ws = new WebSocket('ws://localhost:8000');

      ws.onopen = function() {

        console.log('Connection opened');

      };

      ws.onmessage = function(event) {

        output.innerHTML += '<p>' + event.data + '</p>';

      };

      const input = document.getElementById('input');

      const sendButton = document.getElementById('send');

      sendButton.addEventListener('click', function() {

        ws.send(input.value);

        input.value = '';

      });

    </script>

  </body>

</html>

这段代码中,我们首先定义好前端页面的布局,包含一个用于显示消息的div和一个用于输入消息的输入框和发送按钮。然后我们创建一个websocket对象,定义了当连接打开时和当收到消息时的回调函数,以及发送消息的函数。

通过以上代码的实现,我们就能够构建一个简单的一对一聊天应用,用户可以在前端页面输入信息,发送至后端Node.js服务器,服务器接收到消息后,会实时将该消息转发给另外一个用户。该应用基于websocket通讯方式,具备高效、实时的特点,是一种应用于即时通信领域的佳方案。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复