使用dgram模块实现基于UDP的数据通信
来源:互联网 发布:辐射4低配优化 编辑:程序博客网 时间:2024/03/29 16:46
server.js文件:
var dgram = require("dgram");
//createSocket参数用于指定进行UDP通信时使用的协议类型,可指定值为upd4或upd6
var server = dgram.createSocket("udp4");
//callback参数msg为一个Buffer对象,存放了接收到的数据,rinfo参数值也是一个对象,包含了地址、端口号、字节数等信息
server.on("message",function(msg,rinfo){
console.log("已接收客户端发送的数据:"+msg);
console.log("客户端地址信息为%j",rinfo);
var buf = new Buffer("确认信息:"+msg);
server.send(buf,0,buf.length,rinfo.port,rinfo.address);
setTimeout(function(){
server.unref();
},10000);
});
server.on("listening",function(){
var address = server.address();
console.log("服务器开始监听,地址信息为%j",address);
});
//使用socket端口对象的bind方法来指定该socket端口对象所监听的地址和端口号
//当创建UDP服务器时,必须使用该方法,这样UDP客户端才能知道向哪个地址发送数据
server.bind(41234,'localhost');
client.js文件:
var dgram = require("dgram");
var message = new Buffer("你好");
var client = dgram.createSocket("udp4");
client.send(message,0,message.length,41234,"localhost",function(err,bytes){
if(err){
console.log("发送数据失败");
} else{
console.log("已发送%d字节数据",bytes);
}
});
client.on("message",function(msg,rinfo){
console.log("已接收服务器端发送的数据:%s",msg);
console.log("服务器地址为:%s",rinfo.address);
console.log("服务器所用端口为%s",rinfo.port);
});
分别在两个命令行窗口中执行
node server.js
node client.js
结果:
- 使用dgram模块实现基于UDP的数据通信
- Node.js:dgram模块实现UDP通信
- 【Node dgram模块实现UDP通信】
- 使用net模块实现基于TCP的数据通信
- 12、网络编程之dgram模块(UDP)
- 简单的使用Socket实现数据通信
- Flex 利用ActionScript接口实现Module模块间的数据通信
- python实现的基于TCP的JSON数据通信
- 基于Udp的socket 实现
- 【科研论文】基于DSP的激光跟踪仪数据通信及处理模块设计
- 使用nginx sticky模块实现基于cookie的负载均衡
- 基于LVDS/M-LVDS的数据通信
- LCM UDP数据通信
- 基于Apache Mina实现的UDP服务端
- 基于Apache Mina实现的UDP服务端
- 基于UDP的DayTime服务实现
- 基于UDP的局域网聊天实现
- 基于UDP的H5跨屏实现
- OC学习篇之---@property和@synthesize的使用
- Linq 之添加数据
- Android SDK的安装与环境变量配置
- android TextView 属性大全
- ios实战开发之UIScrollView图片浏览器
- 使用dgram模块实现基于UDP的数据通信
- 常用网址整理
- 【安卓学习问题日志】The project was not built due to "A resource exists with a different case
- 好书推荐
- Set Apache Password Protected Directories With .htaccess File
- 定位功能-单例模式
- HTTP状态码
- Ubuntu的一些使用技巧(不定时更新)
- Objective-C之平铺导航、标签导航、树形结构导航