我试图制作一个从第三方应用程序接收UDP数据包的应用程序。
我尝试在NodeJS中创建服务器UDP,但是现在当我收到数据时,我不知道如何在浏览器窗口中显示它。
我会更好地解释...我的应用程序通过udp实时接收数据,服务器会处理它们,并应在网页上实时显示它们。
这是我在NodeJS中用于UDP服务器的代码:
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
console.log(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
console.log(` messaggio ricevuto ${msg}`);
});
server.on('listening', () => {
const address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind({
adress:'127.0.0.1',
port:'41234'
});
// server listening address :41234
非常感谢您的答复
答案 0 :(得分:1)
欢迎您!
您可以执行以下操作...
// Open a connection
var socket = new WebSocket('ws://localhost:41234/');
// When a connection is made
socket.onopen = function() {
console.log('Opened connection ');
// send data to the server
var json = JSON.stringify({ message: 'Hello ' });
socket.send(json);
}
// When data is received
socket.onmessage = function(event) {
console.log(event.data);
}
// A connection could not be made
socket.onerror = function(event) {
console.log(event);
}
// A connection was closed
socket.onclose = function(code, reason) {
console.log(code, reason);
}
// Close the connection when the window is closed
window.addEventListener('beforeunload', function() {
socket.close();
});
此链接应为您提供更多信息:https://www.sitepoint.com/real-time-apps-websockets-server-sent-events/(上面的摘录摘自该链接)
答案 1 :(得分:0)
您需要Web服务器才能将数据发送到浏览器。
此链接https://socket.io/get-started/chat将帮助您创建网络服务器。
您可以将UDP端口上收到的消息发送到websocket,如下所示:
server.on('message', (msg, rinfo) => {
socket.emit('sendData', msg);
});