纳金网
标题:
Unity - node.js的UDP通信
[打印本页]
作者:
王者再临
时间:
2014-9-26 03:46
标题:
Unity - node.js的UDP通信
1.node server code:
下面是node.js服务器端的node code
var PORT = 33333;
var HOST = '127.0.0.1';
var dgram = require ('dgram');
var server = dgram.createSocket('udp4');
server.on ('listening', function(){
var address = server.address();
console.log('UDP Server listening on ' + address.address + ":" + address.port);
});
server.on('message', function (message, remote) {
console.log(remote.address + ':' + remote.port +' - ' + message);
});
server.bind(PORT, HOST);
2. node Client Code 这里是node的客户端的代码
var PORT = 33333;
var HOST = '127.0.0.1';
var dgram = require ('dgram');
var message = new Buffer('Node js is good');
var client = dgram.createSocket('udp4');
client.send(message, 0, message.length, PORT, HOST, function(err, bytes){
if (err) {
throw err;
}
console.log ('UDP message send to' + HOST + ':' + PORT);
client.close();
});
先运行服务器端的代码,在运行客户端的代码,可以在服务器和客户端看见相关的打印信息。
当然这是运行在node上的。
下面我们只运行node的服务器代码,客户端用unity实现:
unity客户端:
using
UnityEngine
;
using
System
.
Collections
;
using
System
.
Net
.
Sockets
;
using
System
.
Text
;
using
System
;
public
class
node
:
MonoBehaviour
{
void
Start
()
{
}
//
Update
is
called
once
per
frame
void
Update
() {
Debug
.
Log
(
"
Test
"
);
UdpClient
udpClient
=
new
UdpClient
();
udpClient
.
Connect
(
"
127.0.0.1
"
,
33333
);
byte
[]
outStream
=
Encoding
.
UTF8
.
GetBytes
(
"
joining success!
"
);
udpClient
.
Send
(
outStream
,
outStream
.
Length
);
udpClient
.
Close
();
}
//
void
GetConnection
(
IAsyncResult
iar
)
//{
//
Debug
.
Log
(
"
Connection
"
);
//}
}
先运行node的服务器,在运行unity可以看见相关打印信息。自己研究去吧!
作者:
heise
时间:
2014-10-2 01:48
感谢分享!!!!!!!!!!!!
作者:
hyui
时间:
2014-10-2 22:24
Unity with node.js cool !
作者:
moonljj
时间:
2014-10-5 14:01
Unity with node.js cool !
作者:
liuxb21cn
时间:
2014-11-26 18:05
谢谢楼主分享 楼主好人做到底 分享下unity客户端 接收数据的代码呗 谢了
作者:
tianhett
时间:
2014-11-26 21:00
Unity with node.js cool !
欢迎光临 纳金网 (http://go.narkii.com/club/)
Powered by Discuz! X2.5