<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<textarea id="textarea" style="height: 500px; width: 100%;"></textarea>
<input type="button" id="send" onclick="connect()" value="连接">
<input type="button" id="send" onclick="send()" value="给服务端发送消息">
<script type="text/javascript">
//检查浏览器是否支持WebSocket
if (!window.WebSocket) {
console.log('您的浏览器不支持WebSocket,请选择其他的浏览器再尝试连接服务器');
}
let el = document.getElementById("textarea");
try {
const wsClientSp2 = new WebSocket('ws://192.168.32.101:443/TelevisionHub');
wsClientSp2.open = function (e) {
el.value += "连接成功!\r\n";
}
wsClientSp2.onclose = function (e) {
el.value += "连接断开!\r\n";
}
wsClientSp2.onmessage = function (e) {
el.value += "接收消息:" + e.data + "\r\n";
}
wsClientSp2.onerror = function (e) {
el.value += "连接失败!原因【" + JSON.stringify(e) + "】\r\n";
}
// 连接时需要发送该消息
function connect() {
console.log(1, wsClientSp2)
if (wsClientSp2.readyState != 3) {
wsClientSp2.send(`{"protocol":"json","target":"GetDeviceHoles","arguments":[],"type":1,"version":1}${String.fromCharCode(0x1e)}`);
}
console.log(2, wsClientSp2)
}
function send() {
wsClientSp2.send(`{"type":1,"target":"GetDeviceHoles","arguments":[]}${String.fromCharCode(0x1e)}`);
}
} catch (e) {
console.log(e)
}
</script>
</body>
</html>
SignalR hub 的websocket 直连
于 2024-01-11 15:33:37 首次发布
本文介绍了如何在HTML页面中使用WebSocket技术建立与服务器的连接,实现文本输入区实时显示消息以及发送请求的功能。
摘要由CSDN通过智能技术生成