下面是一个简单的 WebSocket 代码示例,展示了如何在客户端使用 JavaScript 创建 WebSocket 连接,并与服务器进行通信。
WebSocket 客户端示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Example</title>
</head>
<body>
<h2>WebSocket Example</h2>
<button id="sendMessage">Send Message</button>
<div id="messages"></div>
<script>
// 创建 WebSocket 连接
const wsUrl = "wss://example.com/socket"; // 替换为实际的 WebSocket URL
const socket = new WebSocket(wsUrl);
// 当连接打开时触发
socket.onopen = function(event) {
console.log("WebSocket is open now.");
socket.send("Hello Server!"); // 向服务器发送一条消息
};
// 接收消息时触发
socket.onmessage = function(event) {
console.log("Message from server: ", event.data);
document.getElementById("messages").innerHTML += "<p>" + event.data + "</p>";
};
// 连接关闭时触发
socket.onclose = function(event) {
console.log("WebSocket is closed now.");
};
// 出现错误时触发
socket.onerror = function(error) {
console.error("WebSocket Error: ", error);
};
// 按钮点击事件,发送消息到服务器
document.getElementById("sendMessage").onclick = function() {
if (socket.readyState === WebSocket.OPEN) { // 确保连接已开启
socket.send("This is a message from the client!");
} else {
console.error("WebSocket is not open. Unable to send message.");
}
};
</script>
</body>
</html>
如何运行该示例
- 将上述代码保存为
index.html
文件。 - 替换
wsUrl
的值为你实际使用的 WebSocket URL(如ws://localhost:8080
或其他有效地址)。 - 在支持 WebSockets 的浏览器中打开该 HTML 文件。
- 点击 “Send Message” 按钮,可以向服务器发送消息并查看从服务器接收到的消息。
注意事项
- 确保你的后端有一个可以接受 WebSocket 连接的服务正在运行。常用的后端技术有 Node.js、Java、Python 等。
- 如果使用的是本地开发环境,请确保跨域和安全设置都配置正确。
内容由零声教学AI助手提供,问题来源于学员提问