HLJ 发布于
2022-11-15 20:16:44

node.js 实现udp传输的实例代码

上一篇文章:

linux常用命令

下一篇文章:

linux常用命令2

服务端 server.js

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}`);
});

server.on('listening', () => {
    const address = server.address();
    console.log(`server listening ${address.address}:${address.port}`);
});

server.bind(41234);
// Prints: server listening 0.0.0.0:41234

客户端client.js

const dgram = require("dgram");
const client = dgram.createSocket('udp4');

client.send('客户端发起的信息!', 41234, 'localhost', (err) => {
    client.close();
});

https://nodejs.org/api/dgram.html#event-close

当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2022-11-15/620.html
最后生成于 2022-11-21 22:22:41
上一篇文章:

linux常用命令

下一篇文章:

linux常用命令2