- 作者:老汪软件技巧
- 发表时间:2024-08-20 11:01
- 浏览量:
在线聊天案例
接下来,V哥基于WebSocket,创建一个在线聊天功能的案例,方便用更好的理解 WebSocket 的应用,以下代码会涉及到前端和后端的编写。来开干:
步骤1:设置后端WebSocket服务器
我们可以使用Node.js和ws库来创建WebSocket服务器。
初始化Node.js项目并安装ws库:
mkdir websocket-chat
cd websocket-chat
npm init -y
npm install ws
创建server.js文件并编写WebSocket服务器代码:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const clients = new Set();
wss.on('connection', function connection(ws) {
clients.add(ws);
ws.on('message', function incoming(message) {
console.log('received: %s', message);
clients.forEach(client => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
ws.on('close', () => {
clients.delete(ws);
});
});
console.log('WebSocket server started on ws://localhost:8080');
步骤2:创建前端页面在项目根目录下创建index.html文件:
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Chattitle>
head>
<body>
<h1>WebSocket Chath1>
<input type="text" id="messageInput" placeholder="Type a message...">
<button id="sendButton">Sendbutton>
<ul id="messagesList">ul>
<script src="chat.js">script>
body>
html>
创建chat.js文件并编写前端逻辑:
const ws = new WebSocket('ws://localhost:8080');
const messageInput = document.getElementById('messageInput');
const sendButton = document.getElementById('sendButton');
const messagesList = document.getElementById('messagesList');
sendButton.addEventListener('click', () => {
const message = messageInput.value;
if (message) {
ws.send(message);
messageInput.value = '';
}
});
ws.onmessage = (event) => {
const messageItem = document.createElement('li');
messageItem.textContent = event.data;
messagesList.appendChild(messageItem);
};
ws.onopen = () => {
console.log('Connected to the WebSocket server.');
};
ws.onclose = () => {
console.log('Disconnected from the WebSocket server.');
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
步骤3:运行WebSocket服务器和前端页面启动WebSocket服务器:
node server.js
打开浏览器并访问file:///path/to/websocket-chat/index.html,替换/path/to/websocket-chat/为你的项目路径。步骤解析:天气预报案例
创建一个基于WebSocket的数据推送天气预报功能,下面 V 哥通过一个案例来演示一下,其中包括一个后端服务器,负责推送天气更新,以及一个前端页面,用于显示实时天气信息。以下是详细的步骤说明和代码解析:
步骤1:设置后端WebSocket服务器
使用Node.js和ws库创建WebSocket服务器。
初始化Node.js项目并安装所需库:
mkdir weather-websocket
cd weather-websocket
npm init -y
npm install ws
创建server.js文件并编写WebSocket服务器代码:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const weatherData = {
temperature: 22, // 假设温度
condition: 'sunny' // 假设天气情况
};
// 定时更新天气数据,模拟实时数据源
setInterval(() => {
weatherData.temperature = Math.floor(Math.random() * 30); // 随机生成温度
weatherData.condition = ['sunny', 'cloudy', 'rainy'][Math.floor(Math.random() * 3)];
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(weatherData));
}
});
}, 5000); // 每5秒更新一次
console.log('WebSocket server started on ws://localhost:8080');
步骤2:创建前端页面在项目根目录下创建index.html文件:
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather Forecasttitle>
head>
<body>
<h1>Live Weather Forecasth1>
<div>
<p>Temperature: <span id="temperature">--span>°Cp>
<p>Condition: <span id="condition">--span>p>
div>
<script src="app.js">script>
body>
html>
创建app.js文件并编写JavaScript代码来处理WebSocket连接和UI更新:
const ws = new WebSocket('ws://localhost:8080');
const temperatureDisplay = document.getElementById('temperature');
const conditionDisplay = document.getElementById('condition');
ws.onmessage = (event) => {
const weather = JSON.parse(event.data);
temperatureDisplay.textContent = weather.temperature;
conditionDisplay.textContent = weather.condition;
};
ws.onopen = () => {
console.log('Connected to the weather WebSocket server.');
};
ws.onclose = () => {
console.log('Disconnected from the weather WebSocket server.');
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
步骤3:运行WebSocket服务器和前端页面启动WebSocket服务器:
node server.js
在浏览器中打开file:///path/to/weather-websocket/index.html,替换/path/to/weather-websocket/为你的项目路径。步骤解析:
注意哦,在实际应用中,天气数据可能来自外部API,如果需要可以在聚合数据上找到,并且需要对数据进行身份验证和加密等安全措施。
最后
WebSocket是一种强大的通信技术,适用于需要实时通信和高交互性的应用场景。掌握利用WebSocket技术,是前端开发的必备技能。欢迎关注威哥爱编程,一起交流学习,不喜勿喷哦。