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