node:12 socketio

安装:

npm i socket.io

原理:(白话版)注册对应的事件,emit抛出事件后触发对应注册的事件。

示例代码:

服务器端:

const express = require("express");

let app = express();
let server = require("http").Server(app); // 通过http协议创建一个服务器
var io = require("socket.io")(server); // 将socket和express进行结合

app.use(express.static(__dirname + "/client"));

// 客户端连接
io.on("connection", function(client){
    client.emit("hehe", "welcome!"); // emit一个'hehe'事件
    client.on("haha", (msg)=>{ // 服务器端注册'haha'事件,当触发'haha'事件时
        console.log("haha"+ msg);
    });
});



server.listen(8081, "127.0.0.1", ()=>{
    console.log("服务端监听8081。。。");
});

浏览器端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="node_modules/socket.io-client/dist/socket.io.js" charset="utf-8"></script>
    <title>Document</title>
</head>
<body>
    
    <script>
        var socket = io.connect("http://127.0.0.1:8081"); // 连接服务器
        socket.on("hehe", function(msg){  // 前端注册'hehe'事件, 当触发'hehe'事件时
            console.log("hehe " + msg);
        });  
        socket.emit("haha", " I am coming!!");  // 前端向后端抛出"haha"事件
    </script>
</body>
</html>
发布了191 篇原创文章 · 获赞 1 · 访问量 4682

猜你喜欢

转载自blog.csdn.net/bluebloodye/article/details/103223309