前端代码
<!--
* @Author: 第一好帅@宝
* @Date: 2023-08-29 16:12:26
* @LastEditTime: 2023-08-29 16:54:50
* @FilePath: \websocket\ceshi.html
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="msg"></div>
<input type="text">
<button>发送</button>
<button class="bu">关闭连接</button>
<div class="box"></div>
<script>
let inp = document.querySelector('input')
let but = document.querySelector('button')
let bu = document.querySelector('.bu')
let ws = new WebSocket('ws://localhost:8001')
console.log(ws);
//初始化连接
ws.onopen = function () {
document.querySelector('.msg').innerHTML = '<h1>连接成功!</h1>'
console.log('连接成功触发函数');
ws.send('第一次连接')
}
//服务器关闭
ws.onclose = function (e) {
document.querySelector('.msg').innerHTML = '<h1>服务器关闭!</h1>'
console.log('服务器关闭');
}
//连接出错
ws.onerror = function (e) {
document.querySelector('.msg').innerHTML = '<h1>连接出错了!</h1>'
console.log('连接出错了');
}
//服务器返回数据触发函数
ws.onmessage = function (e) {
console.log(e.data);
document.querySelector('.box').innerHTML = e.data
}
//向后端发送消息
but.addEventListener('click', function () {
if (inp.value.trim() != '') {
ws.send(inp.value)
}
})
//断开连接
bu.addEventListener('click', function () {
ws.close()
})
</script>
</body>
</html>
后端代码,使用nodejs文章来源:https://www.toymoban.com/news/detail-682314.html
npm i nodejs-websocket
/*
* @Author: 第一好帅@宝
* @Date: 2023-08-29 15:52:49
* @LastEditTime: 2023-08-29 16:48:17
* @FilePath: \node\node.js
*/
var ws = require('nodejs-websocket');
console.log("开始建立连接...");
var server = ws.createServer(function (conn) {
conn.on("connect", function (code) {
console.log("开启连接" + code);
});
conn.on("text", function (result) {
console.log("收到的信息为:" + result); //由Webtest.html中传来data
let a=result
if (result == 1) {
a="飞哥" //发送"success"至Webtest.html
} else if (result == 2) {
a="帆姐" //发送"success"至Webtest.html
} else if (result == 3) {
a='东哥'
}else if(result==4){
a="阳哥"
}
//向前端发送消息
conn.sendText('服务器返回数据:'+a);
});
conn.on("close", function (code) {
console.log("关闭连接")
});
conn.on("error", function (code) {
console.log("异常关闭")
});
}).listen(8001);
console.log("WebSocket连接建立完毕");
运行 node xx.js文章来源地址https://www.toymoban.com/news/detail-682314.html
到了这里,关于webSocket前后端交互pc端版的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!