[前端] node UDP 用户数据报测试


UDP(user datagram protocol)用户数据报协议


dgram是datagram的简写


服务端:udpServer.js

var dgram = require("dgram");

var server = dgram.createSocket("udp4");

server.on("error", function(err) {
    console.log("server error:\n" + err.stack);
    server.close();
});

// 接收来自客户端的消息 server.on("message", function(msg, rinfo) {
    console.log("server got: " + msg.toString() + " from " + rinfo.address + ":" + rinfo.port);
});

// 监听服务 server.on("listening", function() {
    var address = server.address();
    console.log("server listening on " + address.address + ":" + address.port);
});

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

客户端:udpClient.js

var dgram = require('dgram');

var client = dgram.createSocket('udp4');
var message = new Buffer('hello shiyanlou');

client.send(message, 0, message.length, 41234, 'localhost', function(err, bytes) {
    client.close();
});

打开两个cli分别运行代码

服务端cli

$ node server.js

客户端cli

$ node client.js

然后就会在服务端cli发现已经获取了数据



谢谢关注~



你可能感兴趣的:(前端)