Files
ClassContent/历届学生/font-end-nine/项目练习/学生项目/张婷/练习/聊天室/frontend/zlianxi.html
2024-09-27 02:06:13 +08:00

58 lines
1.6 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<textarea name="" placeholder="输入内容" id="" cols="30" rows="10"></textarea>
<button>发送</button>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
var ws = new WebSocket("ws://127.0.0.1:8080")
//以下三个均可省略不写,只需要一定要onmessage
// ws.onopen = function () {
// console.log("连接已经打开");
// }
// ws.onerror = function () {
// console.log("连接产生错误");
// }
// ws.onclose = function () {
// console.log("连接关闭");
// }
ws.onmessage = function (e) {
console.log("收到后端给的消息",e.data);
}
$("button").click(function (){
ws.send($("textarea").val())
console.log($("textarea").val());
})
</script>
</html>
<!-- 后端
const { WebSocketServer } = require("ws");
//创建websocket连接(创建服务端,端口:8080)
const wss = new WebSocketServer({ port: 8080 });
//连接成功触发
//on'connection'监听是否连接成功
wss.on('connection', function connection(ws) {
console.log("一个客户端连接到服务器了..");
//监听消息是否接收
ws.on('message', function message(data) {
console.log('服务器接收到的消息:', data.toString());
ws.send('服务器给前端的消息');
});
}); -->