Created
November 26, 2014 00:56
-
-
Save daicham/1bf2e5836d665bd6b03f to your computer and use it in GitHub Desktop.
Sample UDP Server and Client on node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// UDP Sample Client | |
// UDP 接続先 | |
var host = "localhost"; | |
var c_port = 41234; | |
var dgram = require("dgram"); | |
var client = dgram.createSocket("udp4"); | |
// サーバに送信するメッセージ | |
// var message = new Buffer("hello"); | |
var message = new Buffer("3031323334353637", "hex"); | |
// サーバからメッセージ受信したときの処理 | |
client.on("message", function(msg, rinfo) { | |
console.log("recieved: " + msg.toString("hex")); | |
client.close(); | |
}); | |
// メッセージ送信でエラーが起きた時の処理 | |
client.on("err", function(err) { | |
console.log("client error: \n" + err.stack); | |
console.close(); | |
}); | |
// Socket をクローズした時の処理 | |
client.on("close", function() { | |
console.log("closed."); | |
}); | |
// メッセージ送信 | |
send(message, host, c_port); | |
function send(message, host, port) { | |
client.send(message, 0, message.length, port, host, function(err, bytes) { | |
console.log("sent."); | |
}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// UDP Sample Server | |
// UDP 待受ポート | |
var s_port = 41234; | |
var dgram = require("dgram"); | |
var server = dgram.createSocket("udp4"); | |
// Listen 状態になったときの処理 | |
server.on("listening", function() { | |
var address = server.address(); | |
console.log("server listening " + address.address + ":" + address.port); | |
}); | |
// メッセージを受信した時の処理 | |
server.on("message", function(msg, rinfo) { | |
console.log("server got a message from " + rinfo.address + ":" + rinfo.port); | |
console.log(" HEX : " + msg.toString('hex')); | |
console.log(" ASCII: " + msg); | |
var ack = new Buffer("ack"); | |
server.send(ack, 0, ack.length, rinfo.port, rinfo.address, function(err, bytes) { | |
console.log("sent ACK."); | |
}); | |
}); | |
// メッセージ受信でエラーがあったときの処理 | |
server.on("error", function(err) { | |
console.log("server error: \n" + err.stack); | |
server.close(); | |
}); | |
// Socket がクローズしたときの処理 | |
server.on("close", function() { | |
console.log("closed."); | |
}); | |
// 待受開始 | |
server.bind(s_port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment