在即时通讯的交互方式中websocket是一个很使用的方式,本篇文章讲解在html5中使用websocket
html5是自带websocket的我们可以直接使用但是websocket 是不支持请求头的我们可以使用websocket提供的协议头将需要给后台的信息进行携带
socket = new WebSocket("ws://192.168.0.7:8081",['协议头带的信息']);
//协议头也可以支持字符串形式的发送
socket = new WebSocket("ws://192.168.0.7:8081",'协议头带的信息');
socket.addEventListener("open", function (event) {
console.log("连接事件成功:", event);
});
socket.addEventListener("message", function (event) {
console.log("接收到的消息事件:", event.data);
document.getElementById("wbHtml").innerHTML = "event.data";
});
socket.addEventListener("close", function (event) {
console.log("出错了关闭WebSocket:", event);
document.getElementById("cWHtml").innerHTML = event;
});
socket.addEventListener("error", function (event) {
console.error("WebSocket error报错:", event);
});
function sendMessage() {
let message = document.getElementById("messageInput").value;
if (message) {
socket.send(message);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WebSocket 示例</title>
</head>
<body>
<h1>WebSocket 示例</h1>
<input type="text" id="messageInput" placeholder="请输入要发送的信息" />
<button onclick="sendMessage()">发送消息</button>
</body>
<script>
// 1. 创建一个 WebSocket 对象
let socket;
function cL() {
// 1. 创建一个 WebSocket 对象
socket = new WebSocket("ws://192.168.2.7:8081" "juName=username");
// 2. 监听 WebSocket 连接事件
socket.addEventListener("open", function (event) {
console.log("连接事件成功:", event);
});
// 3. 监听 WebSocket 收到消息事件
socket.addEventListener("message", function (event) {
console.log("接收到的消息事件:", event.data);
document.getElementById("wbHtml").innerHTML = "event.data";
});
// 4. 监听 WebSocket 关闭事件
socket.addEventListener("close", function (event) {
console.log("出错了关闭WebSocket:", event);
document.getElementById("cWHtml").innerHTML = event;
});
// 5. 监听 WebSocket 出错事件
socket.addEventListener("error", function (event) {
console.error("WebSocket error报错:", event);
});
}
// 6、webSocket发送消息
function sendMessage() {
let message = document.getElementById("messageInput").value;
if (message) {
socket.send(message);
}
}
cL();
</script>
</html>