WebSocket是一种在客户端和服务器之间建立持久连接的协议,它允许双方进行双向通信,从而实现低延迟的数据交换。WebSocket非常适合需要实时交互的应用场景,比如聊天应用、在线游戏、实时数据分析等。
WebSocket是一种网络通信协议,它提供了一个全双工的通信通道,允许客户端和服务器端通过TCP连接直接进行数据交换。与HTTP协议不同的是,WebSocket在连接建立之后可以持续不断地发送和接收数据,而不是每次请求都需要重新建立连接。
在客户端,可以通过简单的JavaScript API来创建WebSocket连接。
javascript
深色版本
- 1// 创建WebSocket连接
- 2const socket = new WebSocket('ws://example.com/ws');
- 3
- 4// 连接打开时触发
- 5socket.addEventListener('open', function (event) {
- 6 console.log('Connection opened');
- 7});
- 8
- 9// 接收消息时触发
- 10socket.addEventListener('message', function (event) {
- 11 console.log('Message received:', event.data);
- 12});
- 13
- 14// 连接关闭时触发
- 15socket.addEventListener('close', function (event) {
- 16 console.log('Connection closed');
- 17});
- 18
- 19// 发送消息
- 20socket.send('Hello from client!');
在Node.js环境中,可以使用ws库来轻松创建WebSocket服务器。
ws库bash
深色版本
1npm install ws
javascript
深色版本
- 1const WebSocket = require('ws');
- 2
- 3// 创建WebSocket服务器
- 4const server = new WebSocket.Server({ port: 8080 });
- 5
- 6server.on('connection', function connection(ws) {
- 7 console.log('Client connected');
- 8
- 9 // 当收到客户端的消息时
- 10 ws.on('message', function incoming(message) {
- 11 console.log('received: %s', message);
- 12
- 13 // 向客户端发送消息
- 14 ws.send(`Echo: ${message}`);
- 15 });
- 16
- 17 // 当连接关闭时
- 18 ws.on('close', function close() {
- 19 console.log('Client disconnected');
- 20 });
- 21});
我们将构建一个简单的聊天应用,演示如何使用WebSocket实现实时通信。
深色版本
- 1npm init -y
- 2npm install express ws
创建一个名为server.js的文件,用于设置WebSocket服务器。
javascript
深色版本
- 1const express = require('express');
- 2const WebSocket = require('ws');
- 3
- 4const app = express();
- 5const server = require('http').createServer(app);
- 6const wss = new WebSocket.Server({ server });
- 7
- 8wss.on('connection', function connection(ws) {
- 9 console.log('Client connected');
- 10
- 11 ws.on('message', function incoming(message) {
- 12 console.log('received: %s', message);
- 13 wss.clients.forEach(function each(client) {
- 14 if (client !== ws && client.readyState === WebSocket.OPEN) {
- 15 client.send(message);
- 16 }
- 17 });
- 18 });
- 19
- 20 ws.on('close', function close() {
- 21 console.log('Client disconnected');
- 22 });
- 23});
- 24
- 25app.use(express.static('public'));
- 26
- 27server.listen(3000, function listening() {
- 28 console.log('Listening on %d', server.address().port);
- 29});
在项目的public文件夹中创建一个名为index.html的文件,用于展示聊天界面。
html
深色版本
- 1<!DOCTYPE html>
- 2<html lang="en">
- 3<head>
- 4 <meta charset="UTF-8">
- 5 <title>WebSocket Chat</title>
- 6 <style>
- 7 body { font-family: Arial, sans-serif; }
- 8 #chat { height: 300px; overflow-y: scroll; border: 1px solid #ccc; padding: 10px; }
- 9 input[type=text], button { margin-top: 10px; }
- 10 </style>
- 11</head>
- 12<body>
- 13 <div id="chat"></div>
- 14 <input type="text" id="input" placeholder="Type a message...">
- 15 <button onclick="sendMessage()">Send</button>
- 16
- 17 <script>
- 18 const chatBox = document.getElementById('chat');
- 19 const inputField = document.getElementById('input');
- 20
- 21 // 创建WebSocket连接
- 22 const socket = new WebSocket('ws://localhost:3000/ws');
- 23
- 24 // 连接打开时触发
- 25 socket.addEventListener('open', function (event) {
- 26 console.log('Connection opened');
- 27 });
- 28
- 29 // 接收消息时触发
- 30 socket.addEventListener('message', function (event) {
- 31 const message = event.data;
- 32 const messageElement = document.createElement('p');
- 33 messageElement.textContent = message;
- 34 chatBox.appendChild(messageElement);
- 35 chatBox.scrollTop = chatBox.scrollHeight;
- 36 });
- 37
- 38 // 发送消息
- 39 function sendMessage() {
- 40 const message = inputField.value;
- 41 if (message.trim()) {
- 42 socket.send(message);
- 43 inputField.value = '';
- 44 }
- 45 }
- 46
- 47 // 连接关闭时触发
- 48 socket.addEventListener('close', function (event) {
- 49 console.log('Connection closed');
- 50 });
- 51 </script>
- 52</body>
- 53</html>
node server.js启动服务器。http://localhost:3000。现在,你可以在不同的浏览器窗口或标签页中打开聊天应用,并尝试发送消息,观察消息是否能够在客户端之间实时传输。
通过以上步骤,你已经学会了如何使用WebSocket构建一个简单的聊天应用。WebSocket提供了强大的实时通信能力,使得开发者可以轻松地构建各种实时应用。随着对WebSocket的深入了解,你可以尝试更复杂的应用场景和技术挑战。