我是websockets的新手,我只是想掌握如何从客户端浏览器侦听来自服务器的消息,反之亦然。
我正在使用Node.js/Express设置,只希望能够首先侦听来自客户端的任何消息。
我一直在研究这个https://github.com/websockets/ws库,并尝试了这些示例,但无法在我的本地主机环境中运行。
当我在听消息时,我也不清楚我需要注意什么。
我在客户端使用什么代码,即url +端口,在服务器上使用什么代码?
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost/path', {
perMessageDeflate: false
});发布于 2018-11-14 16:32:55
直接使用websockets可能很麻烦,建议您使用框架来抽象层,这样当客户端不支持websockets时,它们可以很容易地退回到其他方法。例如,这是一个直接使用Express js和Websockets的实现。此示例还允许您对HTTP调用使用相同的服务器。
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
//initialize a simple http server
const server = http.createServer(app);
//initialize the WebSocket server instance
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
//connection is up, let's add a simple simple event
ws.on('message', (message) => {
//log the received message and send it back to the client
console.log('received: %s', message);
ws.send(`Hello, you sent -> ${message}`);
});
//send immediatly a feedback to the incoming connection
ws.send('Hi there, I am a WebSocket server');
});
//start our server
server.listen(3000, () => {
console.log(`Server started on port ${server.address().port} :)`);
});对于客户端,您可以这样做:
const ws = new WebSocket('ws://localhost:3000')
ws.onopen = () => {
console.log('ws opened on browser')
ws.send('hello world')
}
ws.onmessage = (message) => {
console.log(`message received`, message.data)
}正如我在上面提到的,建议您使用一个成熟的websockets框架。如果你的应用程序很小并且不需要缩放,你可以使用任何开源库,socket.io是最受欢迎的。
但是,如果您正在讨论在生产级别上实现这一点,您应该知道开源解决方案不支持可伸缩性、故障转移、消息排序等。在这种情况下,您必须实现一个实时平台作为服务工具。
发布于 2018-11-14 15:48:55
只需注意,socket.io是一个使用websocket的后端/前端库,但如果客户端浏览器不支持websocket,它也有许多后备。下面的示例使用ws后端。
服务器
const WS = require('ws')
const PORT = process.env.PORT || 8080
const wss = new WS.Server({
port: PORT
}, () => console.log(`ws server live on ${PORT}`))
const errHandle = (err) => {
if(err) throw err
}
wss.on('connection', (socket) => {
console.log('something connected')
socket.send('you are connected', errHandle)
socket.on('message', (data) => {
console.log(`socket sent ${data}`)
socket.send('message received', errHandle)
})
})客户端(浏览器)
(() => {
const ws = new WebSocket('ws://localhost:8080')
ws.onopen = () => {
console.log('ws opened on browser')
ws.send('hello world')
}
ws.onmessage = (message) => {
console.log(`message received ${message}`)
}
})()编辑:哦,ws和http是不同的协议。您将需要一个不同的服务器来服务您的http文件
https://stackoverflow.com/questions/53294938
复制相似问题