http协议
http协议特点:
- 无状态协议
- 每个请求是独立的
- 单双工通信,且服务器无法主动给客户端发信息
- http协议受浏览器同源策略影响
http实现双向通信方法:
- 轮询
- 长轮询
- iframe流
- sse EventSource
websocket协议
websocket协议:
- 全双工协议
- 支持跨域
- 支持多种数据格式
客户端
<!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>
<script>
// 服务端提供websocket服务
const ws = new WebSocket("ws://localhost:3000");
ws.onopen = () => {
console.log("客户端连接成功");
// 给服务端发送消息
ws.send("hi server");
};
// 监听服务端数据
ws.onmessage = function (ev) {
console.log("服务端:", ev.data);
};
</script>
</body>
</html>
服务端
import http from "http";
import express from "express";
import { WebSocketServer } from "ws";
const app = express();
const server = http.createServer(app); // http服务
const wss = new WebSocketServer({ server });
wss.on("connection", (ws) => {
console.log("服务端连接成功");
// 给客户端发消息
ws.send("hi client");
// 监听客户端数据
ws.on("message", (msg) => {
console.log("客户端:", msg.toString());
});
});
server.listen(3000);