JS_socket.io简单使用

安装socket.io

npm install --save socket.io

demo目录

├── index.js
├── node_modules
├── package.json
└── views
    └── index.html

服务端代码

./index.js

const http = require('http');
const fs = require('fs');
const socketIO = require('socket.io');
const server = http.createServer((req, res) => {
    let html = fs.readFileSync('./views/index.html');
    res.end(html);
}).listen(3000, '127.0.0.1', () => {
    console.log('socket.io server is running at http://127.0.0.1:3000/');
});


// socket io 操作
const io = socketIO(server);
io.sockets.on('connection', (socket) => {
    console.log('socket.io connected');

    // 监听socket断开事件
    socket.on('disconnect', () => {
        console.log('socket.io disconnected');
    });

    // 轮询进行 服务端推送 自定义事件
    let serverNum = 0;
    setInterval(() => {
        serverNum++;
        socket.emit('server.message', { serverNum: serverNum });
    }, 1000);

    // 监听客户端推送 自定义事件
    socket.on('client.message', (data) => {
        console.log('[client.message]', data)
    });

});

客户端代码

./views/index.html

DOCTYPE html>
<html>

<head>
    <title>demotitle>
head>

<body>
    <h1>socket.io demoh1>
    
    <script src="https://cdn.socket.io/4.4.1/socket.io.min.js">script>

    <script>
        const socket = io.connect('http://127.0.0.1:3000');
        // 监听 socket 连接事件
        socket.on('connection', () => {
            console.log('socket.io connected');
            socket.open();
        });

        // 监听 socket 断开事件
        socket.on('disconnect', () => {
            console.log('socket.io disconnected');
            socket.close();
        });


        let clientNum = 0;
        // 轮询 推送客户端信息 到服务端
        setInterval(() => {
            clientNum++;
            socket.emit('client.message', { clientNum: clientNum });
        }, 1000);

        // 监听服务端 自定义信息事件
        socket.on('server.message', (data) => {
            console.log('[server.message]', data)
        });

    script>
body>

html>

你可能感兴趣的:(#,JS,JS框架,javascript,开发语言,ecmascript)