Home > Web Front-end > JS Tutorial > body text

How to implement an online question and answer system using WebSocket and JavaScript

PHPz
Release: 2023-12-16 17:39:25
Original
866 people have browsed it

How to implement an online question and answer system using WebSocket and JavaScript

WebSocket is a full-duplex communication protocol based on the TCP protocol, which is widely used in Web development to implement real-time communication functions. In this article, we will introduce how to use WebSocket and JavaScript to implement a simple online question and answer system.

  1. Writing HTML page

We first write a basic HTML template and introduce the JavaScript library required by WebSocket into it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>在线问答系统</title>
</head>
<body>
    <div id="messages"></div>
    <form id="message-form">
        <input type="text" id="message-input" placeholder="请输入您的问题...">
        <button type="submit">提交</button>
    </form>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="websocket.js"></script>
</body>
</html>
Copy after login
  1. Writing WebSocket code

We store the WebSocket-related JavaScript code in a separate file. In this file, we need to define several variables and functions and establish a WebSocket connection so that the server can send messages to the client.

// 声明变量
const serverUrl = 'ws://localhost:8080'; // WebSocket服务器地址
const socket = new WebSocket(serverUrl); // WebSocket连接

// 监听WebSocket事件
socket.onopen = function(event) {
    console.log('[WebSocket] 连接成功', event);
};

socket.onclose = function(event) {
    console.log('[WebSocket] 连接关闭', event);
};

socket.onerror = function(event) {
    console.error('[WebSocket] 发生错误', event);
};

socket.onmessage = function(event) {
    console.log('[WebSocket] 收到消息', event);
    showMessage(event.data);
};

// 发送消息到WebSocket服务器
function sendMessage(message) {
    socket.send(message);
}

// 显示消息
function showMessage(message) {
    $('#messages').append($('<p>').text(`机器人:${message}`));
}

// 提交问题
$('#message-form').submit(function(event) {
    event.preventDefault();
    const messageInput = $('#message-input');
    const message = messageInput.val();
    messageInput.val('');
    $('#messages').append($('<p>').text(`你:${message}`));
    sendMessage(message);
});
Copy after login
  1. Writing server code

Finally, we need to write server-side code. In this article, we will use Node.js as the development environment of the server and use the ws library to provide the WebSocket service.

const WebSocketServer = require('ws').Server;

const server = new WebSocketServer({ port: 8080 });

console.log('WebSocket服务器已启动');

// 监听WebSocket连接事件
server.on('connection', function(socket) {
    console.log('WebSocket连接已建立');

    // 监听WebSocket消息事件
    socket.on('message', function(message) {
        console.log('收到消息', message);
        const response = handleQuestion(message);
        socket.send(response);
    });

    // 监听WebSocket关闭事件
    socket.on('close', function() {
        console.log('WebSocket连接已关闭');
    });
});

// 处理问题
function handleQuestion(question) {
    // TODO: 添加问题处理逻辑
    return '这是机器人的回答';
}
Copy after login

In the above code, we create a WebSocketServer object and listen to the connection, message and close events on it. When receiving a message sent by the client, the server will call the handleQuestion function to process it, and then send the reply back to the client.

  1. Testing the online question and answer system

Now, we open two browser windows, one acting as the client and the other acting as the server. Enter your question in the client browser and click the submit button. The server will reply with a message indicating the robot's answer and display it in the client browser.

So far, we have successfully implemented a simple online question and answer system. Of course, this is just a basic example and you can extend and optimize it according to your own needs.

The above is the detailed content of How to implement an online question and answer system using WebSocket and JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template