Node 配合 webseket 订阅 pgsql 的数据表变化

pg订阅 传送门

服务端代码

const {Client} = require('pg');

const WebSocket = require('ws');
const wss = new WebSocket.Server({
    port: 8080, perMessageDeflate: false, verifyClient: (info, cb) => {
        const origin = info.origin || '';
        cb(true);
    },
});

const client = new Client('postgres://chris:postgres@127.0.0.1:5432/postgres')

client.connect().then(() => {
    console.log('Connected to PostGreSQL database');
    client.query('LISTEN watchers');
}).catch((err) => {
    console.error('Error connecting to PostGreSQL database', err);
});

process.on('SIGINT', () => {
    client.end();
    process.exit(0);
});

wss.on('connection', (ws) => {

    console.log('client connection');

    client.on('notification', (notification) => {
        console.log('Received notification:', notification.payload);
        ws.send(`notification:${notification.payload}`);
    });


    ws.on('message', (message) => {
        console.log(`message:${message}`);
        ws.send(`wss:${message}`);
    });

    ws.on('close', () => {
        console.log('connection close');
    });
    
});

客户端 浏览器

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket</title>
</head>
<body>
<script>
    const socket = new WebSocket('ws://localhost:8080');

    // 连接建立时触发
    socket.onopen = function() {
        console.log('connect');
    };

    // 收到服务器消息时触发
    socket.onmessage = function(event) {
        const message = event.data;
        console.log(`message:${message}`);
    };

    // 连接关闭时触发
    socket.onclose = function() {
        console.log('close');
    };

    // 发送消息给服务器
    function sendMessage() {
        const message = 'Hello, server!';
        socket.send(message);
        console.log(`sendMessage:${message}`);
    }
</script>

<button onclick="sendMessage()">sendMessage</button>
</body>
</html>

posted @ 2023-09-05 15:05  vx_guanchaoguo0  阅读(13)  评论(0编辑  收藏  举报