


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.
- 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>
- 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); });
- 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 '这是机器人的回答'; }
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.
- 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



With the continuous development of Internet technology, real-time video streaming has become an important application in the Internet field. To achieve real-time video streaming, the key technologies include WebSocket and Java. This article will introduce how to use WebSocket and Java to implement real-time video streaming playback, and provide relevant code examples. 1. What is WebSocket? WebSocket is a protocol for full-duplex communication on a single TCP connection. It is used on the Web

With the continuous development of Internet technology, real-time communication has become an indispensable part of daily life. Efficient, low-latency real-time communication can be achieved using WebSockets technology, and PHP, as one of the most widely used development languages in the Internet field, also provides corresponding WebSocket support. This article will introduce how to use PHP and WebSocket to achieve real-time communication, and provide specific code examples. 1. What is WebSocket? WebSocket is a single

PHP and WebSocket: Best Practice Methods for Real-Time Data Transfer Introduction: In web application development, real-time data transfer is a very important technical requirement. The traditional HTTP protocol is a request-response model protocol and cannot effectively achieve real-time data transmission. In order to meet the needs of real-time data transmission, the WebSocket protocol came into being. WebSocket is a full-duplex communication protocol that provides a way to communicate full-duplex over a single TCP connection. Compared to H

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How does JavaWebsocket implement online whiteboard function? In the modern Internet era, people are paying more and more attention to the experience of real-time collaboration and interaction. Online whiteboard is a function implemented based on Websocket. It enables multiple users to collaborate in real-time to edit the same drawing board and complete operations such as drawing and annotation. It provides a convenient solution for online education, remote meetings, team collaboration and other scenarios. 1. Technical background WebSocket is a new protocol provided by HTML5. It implements

In this article, we will compare Server Sent Events (SSE) and WebSockets, both of which are reliable methods for delivering data. We will analyze them in eight aspects, including communication direction, underlying protocol, security, ease of use, performance, message structure, ease of use, and testing tools. A comparison of these aspects is summarized as follows: Category Server Sent Event (SSE) WebSocket Communication Direction Unidirectional Bidirectional Underlying Protocol HTTP WebSocket Protocol Security Same as HTTP Existing security vulnerabilities Ease of use Setup Simple setup Complex performance Fast message sending speed Affected by message processing and connection management Message structure Plain text or binary Ease of use Widely available Helpful for WebSocket integration

Golang is a powerful programming language, and its use in WebSocket programming is increasingly valued by developers. WebSocket is a TCP-based protocol that allows two-way communication between client and server. In this article, we will introduce how to use Golang to write an efficient WebSocket server that handles multiple concurrent connections at the same time. Before introducing the techniques, let's first learn what WebSocket is. Introduction to WebSocketWeb

How to use Java and WebSocket to implement real-time stock quotation push Introduction: With the rapid development of the Internet, real-time stock quotation push has become one of the focuses of investors. The traditional stock market push method has problems such as high delay and slow refresh speed. For investors, the inability to obtain the latest stock market information in a timely manner may lead to errors in investment decisions. Real-time stock quotation push based on Java and WebSocket can effectively solve this problem, allowing investors to obtain the latest stock price information as soon as possible.
