能提供完整的代码示例吗
时间: 2023-08-07 17:13:38 浏览: 154
当然可以,以下是一个简单的WebSocket前后端交互的示例代码。
前端代码:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket Demo</title>
</head>
<body>
<input type="text" id="msg">
<button onclick="sendMsg()">发送</button>
<div id="result"></div>
<script>
var socket = new WebSocket("ws://localhost:8080");
socket.onopen = function() {
console.log("WebSocket连接已开启...");
};
socket.onmessage = function(event) {
console.log("收到消息:" + event.data);
document.getElementById("result").innerHTML = event.data;
};
socket.onclose = function() {
console.log("WebSocket连接已关闭...");
};
function sendMsg() {
var msg = document.getElementById("msg").value;
socket.send(msg);
console.log("发送消息:" + msg);
}
</script>
</body>
</html>
```
后端代码:
```
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
console.log("WebSocket服务器已启动...");
wss.on('connection', function(ws) {
console.log("WebSocket连接已建立...");
ws.on('message', function(msg) {
console.log("收到消息:" + msg);
ws.send("已收到消息:" + msg);
});
ws.on('close', function() {
console.log("WebSocket连接已关闭...");
});
});
```
这段代码实现了一个简单的WebSocket聊天室,当用户在前端页面输入消息并点击发送按钮时,前端代码通过WebSocket连接将消息发送到后端。后端代码接收到消息后,将其返回给前端,前端再将其展示在页面上。
阅读全文