8000 UDP message send and receive function · SaffronCode/SaffronCode@a220a8e · GitHub
[go: up one dir, main page]

Skip to content

Commit a220a8e

Browse files
committed
UDP message send and receive function
1 parent 7b17304 commit a220a8e

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

netManager/UDPManager.as

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package netManager
2+
{
3+
import flash.net.DatagramSocket;
4+
import flash.utils.ByteArray;
5+
import flash.events.DatagramSocketDataEvent;
6+
7+
public class UDPManager
8+
{
9+
private static var myUDP:DatagramSocket ;
10+
11+
private static var onReceiveFunction:Function ;
12+
13+
private static function setUp():void
14+
{
15+
if(myUDP==null)
16+
{
17+
myUDP = new DatagramSocket();
18+
myUDP.addEventListener(DatagramSocketDataEvent.DATA,onDataReceived);
19+
}
20+
}
21+
22+
private static function onDataReceived(e:DatagramSocketDataEvent):void
23+
{
24+
trace("Message received");
25+
var message:String = e.data.toString();
26+
if(onReceiveFunction!=null && onReceiveFunction.length>0)
27+
onReceiveFunction(message)
28+
}
29+
30+
private static function getMessageOnPort(onRespond:Function,myPort:uint=43243):void
31+
{
32+
trace("myUDP.connected : "+myUDP.connected);
33+
trace("myUDP.localPort : " +myUDP.localPort);
34+
onReceiveFunction = onRespond ;
35+
if(myUDP.localPort==0 || ( myUDP.localPort!=myPort && myPort!=43243))
36+
{
37+
if(myUDP.connected)
38+
myUDP.close();
39+
40+
myUDP.bind(myPort);
41+
myUDP.receive();
42+
}
43+
}
44+
45+
public static function sendMessageTo(message:String,onRespond:Function,targetIp:String,targetPort:uint):void
46+
{
47+
setUp();
48+
trace("Message sent:"+message);
49+
getMessageOnPort(onRespond);
50+
var data:ByteArray = new ByteArray();
51+
data.writeUTFBytes(message);
52+
myUDP.send(data,0,0,targetIp,targetPort);
53+
myUDP.receive();
54+
}
55+
}
56+
}

0 commit comments

Comments
 (0)
0