Skip to content

Commit d64df15

Browse files
author
jczic
committed
Update events logic
1 parent 3608f83 commit d64df15

File tree

6 files changed

+89
-121
lines changed

6 files changed

+89
-121
lines changed

Diff for: README.md

+18-19
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,18 @@
66
- `"XAsyncSockets.py"`
77

88
#### XAsyncSockets features :
9-
- Managed asynchronous sockets (in pool)
10-
- Works directly with I/O
11-
- Supports very large number of simultaneous pending connections
12-
- Supports concurrent synchronous processing operations if necessary (threaded)
13-
- Implementation of TCP server
14-
- Implementation of TCP client
15-
- Implementation of UDP datagrams sender/receiver
9+
- Managed asynchronous sockets in a pool (up to thousands!)
10+
- Works directly with I/O to receive and send very quickly
11+
- Supports very large number of simultaneous TCP connections
12+
- Supports concurrent synchronous processing operations if necessary (pooled)
13+
- Implementation of TCP servers
14+
- Implementation of TCP clients
15+
- Implementation of UDP datagrams (sender and/or receiver)
1616
- TCP client can event after a specified size of data or a text line received
17-
- Each connections and receivings can pending during a specified time.
17+
- Each connections and receivings can waiting during a specified time
1818
- The reasons of TCP client closures are returned
1919
- Really robust, very fast and easy to use
20-
- Compatible with MicroPython implementation (sockets layer, FiFo queue, perf counter).
20+
- Compatible with MicroPython implementation (sockets layer, FiFo queue, perf counter)
2121

2222
### *XAsyncSockets* classes :
2323

@@ -95,35 +95,34 @@
9595
| Method | Arguments |
9696
| - | - |
9797
| Create (static) | `asyncSocketsPool`, `srvAddr`, `connectTimeout=5`(int), `recvbufLen=4096`(int) |
98-
| AsyncRecvLine | `timeoutSec=None` (int) |
99-
| AsyncRecvData | `size=None` (int), `timeoutSec=None` (int) |
100-
| AsyncSendData | `data` (bytes or buffer protocol) |
101-
| StartSSL* | `keyfile=None`, `certfile=None`, `server_side=False`, `cert_reqs=ssl.CERT_NONE`, `ca_certs=None` |
102-
* StartSSL doesn't works on MycroPython (in asynchronous non-blocking sockets mode)
98+
| AsyncRecvLine | `onDataRecv=None` (function), `onDataRecvArg=None`(object)`, timeoutSec=None` (int) |
99+
| AsyncRecvData | `size=None` (int), `onDataRecv=None` (function), `onDataRecvArg=None`(object), `timeoutSec=None` (int) |
100+
| AsyncSendData | `data` (bytes or buffer protocol), `onDataSent=None` (function), `onDataSentArg=None` (object) |
101+
| StartSSL | `keyfile=None`, `certfile=None`, `server_side=False`, `cert_reqs=ssl.CERT_NONE`, `ca_certs=None` |
102+
- `onDataRecv` is a callback event of type f(xAsyncTCPClient, arg)
103+
- `onDataSent` is a callback event of type f(xAsyncUDPDatagram, arg)
104+
- `StartSSL` doesn't works on MycroPython (in asynchronous non-blocking sockets mode)
103105

104106
| Property | Details |
105107
| - | - |
106108
| SrvAddr | Tuple of ip and port |
107109
| CliAddr | Tuple of ip and port |
108110
| OnFailsToConnect | Get or set an event of type f(xAsyncTCPClient) |
109111
| OnConnected | Get or set an event of type f(xAsyncTCPClient) |
110-
| OnLineRecv | Get or set an event of type f(xAsyncTCPClient, line) |
111-
| OnDataRecv | Get or set an event of type f(xAsyncTCPClient, data) |
112-
| OnCanSend | Get or set an event of type f(xAsyncTCPClient) |
113112

114113
### *XAsyncUDPDatagram* class details :
115114

116115
| Method | Arguments |
117116
| - | - |
118117
| Create (static) | `asyncSocketsPool`, `localAddr=None` (tuple of ip and port), `recvbufLen=4096`(int), `broadcast=False`(bool) |
119-
| AsyncSendDatagram | `datagram` (bytes or buffer protocol), `remoteAddr` (tuple of ip and port) |
118+
| AsyncSendDatagram | `datagram` (bytes or buffer protocol), `remoteAddr` (tuple of ip and port), `onDataSent=None` (function), `onDataSentArg=None` (object) |
119+
- onDataSent is a callback event of type f(xAsyncUDPDatagram, arg)
120120

121121
| Property | Details |
122122
| - | - |
123123
| LocalAddr | Tuple of ip and port |
124124
| OnRecv | Get or set an event of type f(xAsyncUDPDatagram, remoteAddr, datagram) |
125125
| OnFailsToSend | Get or set an event of type f(xAsyncUDPDatagram, datagram, remoteAddr) |
126-
| OnCanSend | Get or set an event of type f(xAsyncUDPDatagram) |
127126

128127
### *XBufferSlot* class details :
129128

Diff for: XAsyncSockets.py

+45-63
Original file line numberDiff line numberDiff line change
@@ -398,7 +398,6 @@ def OnReadyForReading(self) :
398398
except Exception as ex :
399399
asyncTCPCli._close()
400400
raise XAsyncTCPServerException('Error when handling the "OnClientAccepted" event : %s' % ex)
401-
self._asyncSocketsPool.NotifyNextReadyForWriting(asyncTCPCli, True)
402401

403402
# ------------------------------------------------------------------------
404403

@@ -469,9 +468,10 @@ def __init__(self, asyncSocketsPool, cliSocket, srvAddr, cliAddr, bufSlot) :
469468
self._cliAddr = cliAddr if cliAddr else ('0.0.0.0', 0)
470469
self._onFailsToConnect = None
471470
self._onConnected = None
472-
self._onLineRecv = None
473471
self._onDataRecv = None
474-
self._onCanSend = None
472+
self._onDataRecvArg = None
473+
self._onDataSent = None
474+
self._onDataSentArg = None
475475
self._sizeToRead = None
476476
self._rdLinePos = None
477477
self._rdBufView = None
@@ -510,15 +510,16 @@ def OnReadyForReading(self) :
510510
self._rdLinePos = None
511511
self._asyncSocketsPool.NotifyNextReadyForReading(self, False)
512512
self._removeExpireTimeout()
513-
if self._onLineRecv :
513+
if self._onDataRecv :
514+
line = self._bufSlot.Buffer[:lineLen]
514515
try :
515-
line = self._bufSlot.Buffer[:lineLen].decode()
516+
line = line.decode()
516517
except :
517-
break
518+
pass
518519
try :
519-
self._onLineRecv(self, line)
520+
self._onDataRecv(self, line, self._onDataRecvArg)
520521
except Exception as ex :
521-
raise XAsyncTCPClientException('Error when handling the "OnLineRecv" event : %s' % ex)
522+
raise XAsyncTCPClientException('Error when handling the "OnDataRecv" event : %s' % ex)
522523
break
523524
elif b != b'\r' :
524525
if self._rdLinePos < self._bufSlot.Size :
@@ -549,8 +550,9 @@ def OnReadyForReading(self) :
549550
self._removeExpireTimeout()
550551
if self._onDataRecv :
551552
size = self._sizeToRead if self._sizeToRead else n
553+
data = memoryview(self._bufSlot.Buffer)[:size]
552554
try :
553-
self._onDataRecv(self, memoryview(self._bufSlot.Buffer)[:size])
555+
self._onDataRecv(self, data, self._onDataRecvArg)
554556
except Exception as ex :
555557
raise XAsyncTCPClientException('Error when handling the "OnDataRecv" event : %s' % ex)
556558
else :
@@ -586,28 +588,30 @@ def OnReadyForWriting(self) :
586588
self._wrBufView = self._wrBufView[n:]
587589
if self._wrBufView :
588590
return
589-
self._asyncSocketsPool.NotifyNextReadyForWriting(self, False)
590-
if self._onCanSend :
591-
try :
592-
self._onCanSend(self)
593-
except Exception as ex :
594-
raise XAsyncTCPClientException('Error when handling the "OnCanSend" event : %s' % ex)
591+
self._asyncSocketsPool.NotifyNextReadyForWriting(self, False)
592+
if self._onDataSent :
593+
try :
594+
self._onDataSent(self, self._onDataSentArg)
595+
except Exception as ex :
596+
raise XAsyncTCPClientException('Error when handling the "OnDataSent" event : %s' % ex)
595597

596598
# ------------------------------------------------------------------------
597599

598-
def AsyncRecvLine(self, timeoutSec=None) :
600+
def AsyncRecvLine(self, onDataRecv=None, onDataRecvArg=None, timeoutSec=None) :
599601
if self._rdLinePos is not None or self._rdBufView :
600602
raise XAsyncTCPClientException('AsyncRecvLine : Already waiting asynchronous receive.')
601603
if self._socket :
602604
self._setExpireTimeout(timeoutSec)
603-
self._rdLinePos = 0
605+
self._rdLinePos = 0
606+
self._onDataRecv = onDataRecv
607+
self._onDataRecvArg = onDataRecvArg
604608
self._asyncSocketsPool.NotifyNextReadyForReading(self, True)
605609
return True
606610
return False
607611

608612
# ------------------------------------------------------------------------
609613

610-
def AsyncRecvData(self, size=None, timeoutSec=None) :
614+
def AsyncRecvData(self, size=None, onDataRecv=None, onDataRecvArg=None, timeoutSec=None) :
611615
if self._rdLinePos is not None or self._rdBufView :
612616
raise XAsyncTCPClientException('AsyncRecvData : Already waiting asynchronous receive.')
613617
if self._socket :
@@ -624,21 +628,25 @@ def AsyncRecvData(self, size=None, timeoutSec=None) :
624628
else :
625629
self._sizeToRead = size
626630
self._setExpireTimeout(timeoutSec)
627-
self._rdBufView = memoryview(self._bufSlot.Buffer)[:size]
631+
self._rdBufView = memoryview(self._bufSlot.Buffer)[:size]
632+
self._onDataRecv = onDataRecv
633+
self._onDataRecvArg = onDataRecvArg
628634
self._asyncSocketsPool.NotifyNextReadyForReading(self, True)
629635
return True
630636
return False
631637

632638
# ------------------------------------------------------------------------
633639

634-
def AsyncSendData(self, data) :
640+
def AsyncSendData(self, data, onDataSent=None, onDataSentArg=None) :
635641
if self._socket :
636642
try :
637643
if bytes([data[0]]) :
638644
if self._wrBufView :
639645
self._wrBufView = memoryview(self._wrBufView.tobytes() + data)
640646
else :
641647
self._wrBufView = memoryview(data)
648+
self._onDataSent = onDataSent
649+
self._onDataSentArg = onDataSentArg
642650
self._asyncSocketsPool.NotifyNextReadyForWriting(self, True)
643651
return True
644652
except :
@@ -708,27 +716,6 @@ def OnConnected(self) :
708716
def OnConnected(self, value) :
709717
self._onConnected = value
710718

711-
@property
712-
def OnLineRecv(self) :
713-
return self._onLineRecv
714-
@OnLineRecv.setter
715-
def OnLineRecv(self, value) :
716-
self._onLineRecv = value
717-
718-
@property
719-
def OnDataRecv(self) :
720-
return self._onDataRecv
721-
@OnDataRecv.setter
722-
def OnDataRecv(self, value) :
723-
self._onDataRecv = value
724-
725-
@property
726-
def OnCanSend(self) :
727-
return self._onCanSend
728-
@OnCanSend.setter
729-
def OnCanSend(self, value) :
730-
self._onCanSend = value
731-
732719
# ============================================================================
733720
# ===( XAsyncUDPDatagram )====================================================
734721
# ============================================================================
@@ -763,7 +750,6 @@ def Create(asyncSocketsPool, localAddr=None, recvbufLen=4096, broadcast=False) :
763750
xAsyncUDPDatagram = XAsyncUDPDatagram(asyncSocketsPool, udpSocket, bufSlot)
764751
if openRecv :
765752
asyncSocketsPool.NotifyNextReadyForReading(xAsyncUDPDatagram, True)
766-
asyncSocketsPool.NotifyNextReadyForWriting(xAsyncUDPDatagram, True)
767753
return xAsyncUDPDatagram
768754

769755
# ------------------------------------------------------------------------
@@ -773,8 +759,9 @@ def __init__(self, asyncSocketsPool, udpSocket, bufSlot) :
773759
super().__init__(asyncSocketsPool, udpSocket, bufSlot)
774760
self._wrDgramFiFo = XFiFo()
775761
self._onFailsToSend = None
776-
self._onCanSend = None
777-
self._onRecv = None
762+
self._onDataSent = None
763+
self._onDataSentArg = None
764+
self._onDataRecv = None
778765
except :
779766
raise XAsyncUDPDatagramException('Error to creating XAsyncUDPDatagram, arguments are incorrects.')
780767

@@ -793,11 +780,11 @@ def OnReadyForReading(self) :
793780
datagram = memoryview(buf)
794781
except :
795782
return
796-
if self._onRecv :
783+
if self._onDataRecv :
797784
try :
798-
self._onRecv(self, remoteAddr, datagram)
785+
self._onDataRecv(self, remoteAddr, datagram)
799786
except Exception as ex :
800-
raise XAsyncUDPDatagramException('Error when handling the "OnRecv" event : %s' % ex)
787+
raise XAsyncUDPDatagramException('Error when handling the "OnDataRecv" event : %s' % ex)
801788

802789

803790
# ------------------------------------------------------------------------
@@ -818,19 +805,21 @@ def OnReadyForWriting(self) :
818805
if not self._wrDgramFiFo.Empty :
819806
return
820807
self._asyncSocketsPool.NotifyNextReadyForWriting(self, False)
821-
if self._onCanSend :
808+
if self._onDataSent :
822809
try :
823-
self._onCanSend(self)
810+
self._onDataSent(self, self._onDataSentArg)
824811
except Exception as ex :
825-
raise XAsyncUDPDatagramException('Error when handling the "OnCanSend" event : %s' % ex)
812+
raise XAsyncUDPDatagramException('Error when handling the "OnDataSent" event : %s' % ex)
826813

827814
# ------------------------------------------------------------------------
828815

829-
def AsyncSendDatagram(self, datagram, remoteAddr) :
816+
def AsyncSendDatagram(self, datagram, remoteAddr, onDataSent=None, onDataSentArg=None) :
830817
if self._socket :
831818
try :
832819
if bytes([datagram[0]]) and len(remoteAddr) == 2 :
833820
self._wrDgramFiFo.Put( (datagram, remoteAddr) )
821+
self._onDataSent = onDataSent
822+
self._onDataSentArg = onDataSentArg
834823
self._asyncSocketsPool.NotifyNextReadyForWriting(self, True)
835824
return True
836825
except :
@@ -848,11 +837,11 @@ def LocalAddr(self) :
848837
return ('0.0.0.0', 0)
849838

850839
@property
851-
def OnRecv(self) :
852-
return self._onRecv
853-
@OnRecv.setter
854-
def OnRecv(self, value) :
855-
self._onRecv = value
840+
def OnDataRecv(self) :
841+
return self._onDataRecv
842+
@OnDataRecv.setter
843+
def OnDataRecv(self, value) :
844+
self._onDataRecv = value
856845

857846
@property
858847
def OnFailsToSend(self) :
@@ -861,13 +850,6 @@ def OnFailsToSend(self) :
861850
def OnFailsToSend(self, value) :
862851
self._onFailsToSend = value
863852

864-
@property
865-
def OnCanSend(self) :
866-
return self._onCanSend
867-
@OnCanSend.setter
868-
def OnCanSend(self, value) :
869-
self._onCanSend = value
870-
871853
# ============================================================================
872854
# ===( XBufferSlot )==========================================================
873855
# ============================================================================

Diff for: tcpCli.py

+9-18
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,17 @@ def _onTCPClientFailsToConnect(xAsyncTCPClient) :
77

88
def _onTCPClientConnected(xAsyncTCPClient) :
99
print("On TCP Client Connected")
10-
xAsyncTCPClient.AsyncSendData(b'Hello World')
11-
xAsyncTCPClient.AsyncRecvData()
10+
xAsyncTCPClient.AsyncSendData( data = b'Hello World',
11+
onDataSent = _onTCPClientDataSent,
12+
onDataSentArg = 'test' )
13+
xAsyncTCPClient.AsyncRecvData(onDataRecv=_onTCPClientDataRecv)
1214

13-
def _onTCPClientLineRecv(xAsyncTCPClient, line) :
14-
print("On TCP Client Line Recv : %s" % line)
15-
xAsyncTCPClient.AsyncRecvLine()
15+
def _onTCPClientDataSent(xAsyncTCPClient, arg) :
16+
print("On TCP Client Data Sent (%s)" % arg)
1617

17-
def _onTCPClientDataRecv(xAsyncTCPClient, data) :
18-
global countRecv
19-
countRecv += 1
20-
print( "%s) On TCP Client Data Recv (%s bytes) : %s" \
21-
% (countRecv, len(data), data.tobytes()) )
22-
xAsyncTCPClient.AsyncRecvData()
23-
24-
def _onTCPClientCanSend(xAsyncTCPClient) :
25-
print("On TCP Client Can Send")
18+
def _onTCPClientDataRecv(xAsyncTCPClient, data, arg) :
19+
print("On TCP Client Data Recv (%s bytes) : %s" % (len(data), data.tobytes()))
20+
xAsyncTCPClient.AsyncRecvData(onDataRecv=_onTCPClientDataRecv)
2621

2722
def _onTCPClientClosed(xAsyncTCPClient, closedReason) :
2823
global countClosed
@@ -39,7 +34,6 @@ def _onTCPClientClosed(xAsyncTCPClient, closedReason) :
3934
reason = "???"
4035
print("%s) On TCP Client Closed (%s)" % (countClosed, reason))
4136

42-
countRecv = 0
4337
countClosed = 0
4438

4539
pool = XAsyncSocketsPool()
@@ -51,9 +45,6 @@ def _onTCPClientClosed(xAsyncTCPClient, closedReason) :
5145
print("Client %s created" % (i+1))
5246
cli.OnFailsToConnect = _onTCPClientFailsToConnect
5347
cli.OnConnected = _onTCPClientConnected
54-
cli.OnLineRecv = _onTCPClientLineRecv
55-
cli.OnDataRecv = _onTCPClientDataRecv
56-
cli.OnCanSend = _onTCPClientCanSend
5748
cli.OnClosed = _onTCPClientClosed
5849
else :
5950
print("Error to create client %s..." % (i+1))

Diff for: tcpSrv.py

+6-14
Original file line numberDiff line numberDiff line change
@@ -6,28 +6,20 @@ def _onTCPSrvClientAccepted(xAsyncTCPServer, xAsyncTCPClient) :
66
global countAccepted
77
countAccepted += 1
88
print('%s) On TCP Server Client Accepted' % countAccepted)
9-
xAsyncTCPClient.OnLineRecv = _onTCPClientLineRecv
10-
xAsyncTCPClient.OnDataRecv = _onTCPClientDataRecv
11-
xAsyncTCPClient.OnCanSend = _onTCPClientCanSend
12-
xAsyncTCPClient.OnClosed = _onTCPClientClosed
13-
xAsyncTCPClient.AsyncRecvData(timeoutSec=1)
9+
xAsyncTCPClient.OnClosed = _onTCPClientClosed
10+
xAsyncTCPClient.AsyncRecvData( onDataRecv = _onTCPClientDataRecv,
11+
onDataRecvArg = 'test',
12+
timeoutSec = 1 )
1413

1514
def _onTCPSrvClosed(xAsyncTCPServer, closedReason) :
1615
print("On TCP Server Closed")
1716

18-
def _onTCPClientLineRecv(xAsyncTCPClient, line) :
19-
print("On TCP Client Line Recv : %s" % line)
20-
xAsyncTCPClient.AsyncRecvLine(timeoutSec=2)
21-
22-
def _onTCPClientDataRecv(xAsyncTCPClient, data) :
17+
def _onTCPClientDataRecv(xAsyncTCPClient, data, arg) :
2318
global countRecv
2419
countRecv += 1
2520
print( "%s) On TCP Client Data Recv (%s bytes) : %s" \
2621
% (countRecv, len(data), data.tobytes()) )
27-
xAsyncTCPClient.AsyncRecvData(timeoutSec=2)
28-
29-
def _onTCPClientCanSend(xAsyncTCPClient) :
30-
print("On TCP Client Can Send")
22+
xAsyncTCPClient.AsyncRecvData(onDataRecv=_onTCPClientDataRecv, timeoutSec=2)
3123

3224
def _onTCPClientClosed(xAsyncTCPClient, closedReason) :
3325
global countClosed

0 commit comments

Comments
 (0)