Home >Web Front-end >JS Tutorial >How to implement a real-time online complaint system using WebSocket and JavaScript
How to use WebSocket and JavaScript to implement a real-time online complaint system
Abstract: This article describes how to use WebSocket and JavaScript to build a real-time online complaint system. Through the two-way communication feature of WebSocket, real-time communication between users and administrators can be achieved, and specific code examples are provided.
<!DOCTYPE html> <html> <head> <title>实时在线投诉系统</title> </head> <body> <h1>实时在线投诉系统</h1> <textarea id="complaints" rows="5" cols="50"></textarea><br> <button onclick="sendComplaint()">发送投诉</button><br> <div id="replies"></div> </body> </html>
var socket = new WebSocket('wss://your-websocket-server.com'); socket.onopen = function() { console.log('WebSocket连接已建立'); }; socket.onmessage = function(event) { var reply = event.data; document.getElementById('replies').innerHTML += '<p>' + reply + '</p>'; }; socket.onclose = function() { console.log('WebSocket连接已关闭'); }; function sendComplaint() { var complaints = document.getElementById('complaints').value; socket.send(complaints); }
In this code, we first create a WebSocket object and specify the server address to connect to. We then handle the opening of connections, the arrival of messages, and the closing of connections by defining some event handlers. Finally, we define a function to send complaints, which sends the complaint content to the server.
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function(ws) { ws.on('message', function(message) { console.log('接收到投诉:' + message); // 处理投诉逻辑,并返回回复 var reply = '感谢您的投诉,我们会尽快处理。'; ws.send(reply); }); });
In this example, we first create a WebSocket server and specify the listening port. When a new connection is established, the server will execute the callback function. In the callback function, we receive the message from the client and handle the complaint logic. Finally, we send the reply to the client through the send method of the WebSocket object.
Reference materials:
The above is the detailed content of How to implement a real-time online complaint system using WebSocket and JavaScript. For more information, please follow other related articles on the PHP Chinese website!