Attachment 'UDP.v1.0.txt'
Download 1 :Class UDP
2 ⍝ Class for Asynchronous UDP/IP Communication
3
4 ⍝ List of methods:
5 ⍝ SendReceive = Send the bytes and return the bytes received
6
7 ⍝ Version 1.0 January 2016
8
9 ⍝ .Net assemblies:
10 :Using
11 :Using System.Net,System.dll
12 :Using System.Net.Sockets,System.dll
13
14 :Field Public udpObj
15 :Field Public Type←'UDP'
16 :Field Public _Retries←3 ⍝ Number of retries if no answer from remote host.
17 :Field Public _PortTimeOut←250 ⍝ Time in milliseconds to Wait for a UdpClient that is not Active (Receiving Nothing).
18
19 (⎕IO ⎕ML ⎕WX)←1 3 3 ⍝ System variables
20
21 ∇ Init0
22 :Access Public
23 :Implements Constructor
24 ∇
25
26 ∇ r←SendReceive(bytes ip port);data;ipep;retries;task
27 :Access Public
28 ⍝ Send the bytes and return the bytes received
29 ⍝ bytes = Bytes (as Numbers 0 to 255) to be Written to the Communication Port
30 ⍝ ip = IP Address where to send the bytes in characters ('192.168.1.1') or numbers (192 168 1 1)
31 ⍝ port = Port Number to send the bytes (0 - 65535)
32 ⍝
33 ⍝ r[1] = 1 for Success, 0 for Failure
34 ⍝ r[2] = Response if Success, Literal Error if Failure
35
36 :Trap 0
37 ⍝ Prepare the IP adress:
38 :If ' '=↑1↑0⍴ip ⍝ Characters ?
39 ip←IPAddress.Parse(⊂,ip)
40 ip←⎕NEW IPAddress(ip.Address)
41
42 :Else ⍝ Numbers
43 ip←⎕NEW IPAddress(⊂,ip)
44
45 :EndIf
46
47 ⍝ Prepare the IPEndPoint
48 ipep←⎕NEW IPEndPoint(ip port)
49
50 ⍝ Prepare the UdpClient
51 udpObj←⎕NEW UdpClient
52
53 retries←_Retries
54
55 ⍝ Loop until some data is received
56 :While retries>0
57
58 ⍝ Send the data asynchronously to the IPEndPoint
59 task←udpObj.SendAsync(bytes(⍬⍴⍴,bytes)ipep) ⍝ Prepare the task
60
61 :If 0=⎕TSYNC{task.Wait ⍵}&(_PortTimeOut)
62 ⍝ Failure to send all the data.
63 r←0 'UDP Error Sending: Task did not complete sending the bytes' ⋄ →RETRIES
64 :Else
65 ⍝ Success
66 task.Dispose
67 :EndIf
68
69 ⍝ Receive the data asynchronously
70 task←udpObj.ReceiveAsync ⍝ Prepare the task
71
72 :If ⎕TSYNC{task.Wait ⍵}&(_PortTimeOut)
73 ⍝ Task completed successfully
74 data←task.Result.Buffer
75 task.Dispose
76 r←1 data
77 :Else
78 ⍝ taskResult=0 when no data is received
79 r←0 'UDP: No Data Received' ⋄ →RETRIES
80 :EndIf
81
82 RETRIES: retries-←1
83
84 :Until 1=1↑r
85
86 ⍝ Clean-up
87 :Trap 0
88 udpObj.Close
89 udpObj←⎕NULL
90 :EndTrap
91
92 :Else
93 ⍝ Show the error.
94 :If 90=⎕EN
95 ⍝ .Net Error
96 r←0('UDP Error: ',⎕EXCEPTION.GetBaseException.Message) ⋄ →0
97 :Else
98 ⍝ APL Error
99 r←0(1⊃⎕DM),': ',{(' '=1↑⍵)↓((1↓a,0)∨a←' '≠⍵)/⍵}(2⊃⎕DM) ⋄ →0
100 :EndIf
101 :EndTrap
102 ∇
103 :EndClass
Attached Files
To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.You are not allowed to attach a file to this page.