File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ <!DOCTYPE html>
2+ < html lang ="en ">
3+
4+ < head >
5+ < meta charset ="UTF-8 ">
6+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 ">
7+ < title > Document</ title >
8+ </ head >
9+
10+ < body >
11+ < script src ="https://cdn.socket.io/4.5.4/socket.io.min.js "> </ script >
12+
13+ < script >
14+ const socket = io ( "http://localhost:3000" ) ;
15+
16+ socket . emit ( "message" , "你好服务器!" ) ;
17+
18+ socket . on ( "reply" , ( msg ) => {
19+ console . log ( "服务器回复:" , msg ) ;
20+ } ) ;
21+ </ script >
22+ </ body >
23+
24+ </ html >
Original file line number Diff line number Diff line change 1+ const io = require("socket.io")(3000);
2+
3+ io.on("connection", (socket) => {
4+ console.log("用户连接成功:", socket.id);
5+
6+ socket.on("message", (data) => {
7+ console.log("收到消息:", data);
8+
9+ socket.emit("reply", "服务器收到!");
10+ });
11+
12+ socket.on("disconnect", () => {
13+ console.log("用户断开连接");
14+ });
15+ });
Original file line number Diff line number Diff line change 1+ const ws = new WebSocket ( "地址" ) ; // 创建websocket连接,浏览器自动握手
2+
3+ // 事件:握手完成后触发
4+ ws . onopen = function ( ) {
5+ console . log ( '连接到了服务器' ) ;
6+ } ;
7+ // 事件:收到服务器消息后触发
8+ ws . onmessage = function ( e ) {
9+ console . log ( e . data ) ; // e.data:服务器发送的消息
10+ } ;
11+ // 事件:连接关闭后触发
12+ ws . onclose = function ( ) {
13+ console . log ( '连接关闭了' ) ;
14+ } ;
15+
16+ // 发送消息到服务器
17+ ws . send ( 消息 ) ;
18+ // 连接状态:0-正在连接中 1-已连接 2-正在关闭中 3-已关闭
19+ ws . readyState
You can’t perform that action at this time.
0 commit comments