当前位置: 首页 > 工具软件 > SAEA.Socket > 使用案例 >

Express socket(基于socket.io.js)

卢承弼
2023-12-01

Express Socket

基于 socket.io.js

Server端代码:

//https://github.com/socketio/socket.io
//与express结合
//注意跨域问题
const express = require("express"),
    app = express(),
    server = require("http").createServer(app),
    io = require("socket.io")(server),
    path = require("path");

io.on("connection", client => {
    client.emit("hehe", "你好!");
    client.on("haha", msg => {
        console.log("haha", msg);
    });
});

//静态资源访问的相对路径,用于html中的js加载
app.use(express.static("./"));//路径指向 相对的文件夹路径

app.use("/index", function (req, res) {
    res.sendFile(path.join(__dirname, "index.html"))
});
let ws = server.listen(3000, function () {
    console.log('start at port:' + ws.address().port);
});
// app.set("port", 3000); //可以不用这个
// let ws = server.listen(app.settings.port, function () {
//     console.log('start at port:' + ws.address().port);
// });

//这样不行
// app.listen(3333, "127.0.0.1", function (err) {
//     if (err) {
//         console.log("监听失败");
//         throw err;
//     }
//
//     console.log("server 已经开启,默认IP: 127.0.0.1, Port:3333");
// });


Client端的代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Socket.io Client</title>
    <script src="socket.io.js"></script>
</head>
<body>
<script>
    //这3种方式都可以
    //io()不传参数的话,会自动获取当前的访问路径
    // let client = io("http://localhost:3000", {});

    // let client = io({
    //     hostname: "localhost",
    //     path: "/socket.io",
    //     port: "3000"
    // });

    let client = io();
    client.on("hehe", msg => {
        // console.log("hehe", msg);
        document.body.innerHTML = "<h1>hehe: " + msg + "</h1>";
    });
    client.emit("haha", "我很好!");
</script>
</body>
</html>
 类似资料: