58 lines
1.6 KiB
HTML
58 lines
1.6 KiB
HTML
<!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('服务器给前端的消息');
|
||
});
|
||
|
||
|
||
}); --> |