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:[email protected]: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>
标签:Node,webseket,console,log,notification,数据表,ws,const,message
From: https://www.cnblogs.com/guanchaoguo/p/17679681.html