1/* 本测试case,测试udp的接口,接口返回值等,udp server是公网udp服务器:47.101.151.113 */ 2function ArrayToString(fileData){ 3 var dataString = ""; 4 for (var i = 0; i < fileData.length; i++) { 5 dataString += String.fromCharCode(fileData[i]); 6 } 7 8 return dataString; 9 } 10 11console.log('udp: testing udp...'); 12// 测试 udp 模块 13var udp = require('udp'); 14if(!(udp && udp.createSocket)){ 15 throw new Error("udp: [failed] require(\'udp\')"); 16} 17 18console.log('udp: [success] require(\'udp\')'); 19 20var udpSocket = udp.createSocket(); 21// 测试 UDPSocket 接口 22if(!udpSocket || !udpSocket.bind || !udpSocket.send || !udpSocket.close || !udpSocket.on) { 23 throw new Error("udp: [failed] udp instance"); 24} 25 26// 测试接收数据 27var sendCnt = 0, recvCnt = 0; 28var defaultMessage = 'AMP udp server reply'; 29udpSocket.on('message', function(message, rinfo) { 30 if(!message || typeof message !== 'object' || ArrayToString(message) !== defaultMessage) { 31 throw new Error("udp: [failed] udp receive message"); 32 } 33 if(!rinfo || !rinfo.host || !rinfo.port) { 34 throw new Error("udp: [failed] udp receive rinfo"); 35 } 36 recvCnt ++; 37 console.log('udp: [debug] remote[' + rinfo.host + ': ' + rinfo.port + '] on message: ' + ArrayToString(message) + ', cnt: ' + recvCnt); 38 if(recvCnt >= 10){ 39 udpSocket.close(); 40 console.log('udp: [success] udp.on(\'message\')'); 41 console.log('udp: testing udp success'); 42 } 43}); 44 45// 接收数据超时 46setTimeout(function() { 47 if(recvCnt != 10) { 48 console.log('udp: [failed] udp on message'); 49 } 50}, 12000); 51 52// 测试socket异常 53udpSocket.on('error', function(err) { 54 console.log('udp error ', err); 55 throw new Error("udp: [failed] udp on error"); 56}); 57 58// 测试发送数据 59var intervalHandle = setInterval(function() { 60 udpSocket.send({ 61 address: "47.101.151.113", 62 port: 50000, 63 message: "this is xxw, cnt: " + sendCnt, 64 success: function() { 65 sendCnt ++; 66 console.log("udp: [debug] send success, cnt: ", sendCnt); 67 // 退出发送 68 if(sendCnt >= 10){ 69 clearInterval(intervalHandle); 70 console.log('udp: [success] udp.send()'); 71 } 72 }, 73 fail: function() { 74 console.log("udp: send fail"); 75 throw new Error("udp: [failed] udp send fail"); 76 } 77 }); 78}, 1000); 79 80udpSocket.bind(10240); 81if(!udpSocket.localPort || typeof udpSocket.localPort !== 'number') { 82 throw new Error("udp: [failed] udp localPort"); 83} 84 85console.log('udp: [success] udp.localPort');