summary refs log tree commit diff stats
path: root/lib/pure/asyncio.nim
diff options
context:
space:
mode:
Diffstat (limited to 'lib/pure/asyncio.nim')
-rw-r--r--lib/pure/asyncio.nim29
1 files changed, 17 insertions, 12 deletions
diff --git a/lib/pure/asyncio.nim b/lib/pure/asyncio.nim
index 4ff6e0ced..c4a07d751 100644
--- a/lib/pure/asyncio.nim
+++ b/lib/pure/asyncio.nim
@@ -89,13 +89,13 @@ import sockets, os
 ##      getSocket(s).accept(client)
 
 when defined(windows):
-  from winlean import TTimeVal, TFdSet, FD_ZERO, FD_SET, FD_ISSET, select
+  from winlean import TTimeVal, TSocketHandle, TFdSet, FD_ZERO, FD_SET, FD_ISSET, select
 else:
-  from posix import TTimeVal, TFdSet, FD_ZERO, FD_SET, FD_ISSET, select
+  from posix import TTimeVal, TSocketHandle, TFdSet, FD_ZERO, FD_SET, FD_ISSET, select
 
 type
   TDelegate* = object
-    fd*: cint
+    fd*: TSocketHandle
     deleVal*: PObject
 
     handleRead*: proc (h: PObject) {.nimcall.}
@@ -213,6 +213,7 @@ proc asyncSockHandleRead(h: PObject) =
   else:
     PAsyncSocket(h).handleAccept(PAsyncSocket(h))
 
+proc close*(sock: PAsyncSocket)
 proc asyncSockHandleWrite(h: PObject) =
   when defined(ssl):
     if PAsyncSocket(h).socket.isSSL and not
@@ -230,15 +231,19 @@ proc asyncSockHandleWrite(h: PObject) =
   else:
     if PAsyncSocket(h).sendBuffer != "":
       let sock = PAsyncSocket(h)
-      let bytesSent = sock.socket.sendAsync(sock.sendBuffer)
-      assert bytesSent > 0
-      if bytesSent != sock.sendBuffer.len:
-        sock.sendBuffer = sock.sendBuffer[bytesSent .. -1]
-      elif bytesSent == sock.sendBuffer.len:
-        sock.sendBuffer = ""
-      
-      if PAsyncSocket(h).handleWrite != nil:
-        PAsyncSocket(h).handleWrite(PAsyncSocket(h))
+      try:
+        let bytesSent = sock.socket.sendAsync(sock.sendBuffer)
+        assert bytesSent > 0
+        if bytesSent != sock.sendBuffer.len:
+          sock.sendBuffer = sock.sendBuffer[bytesSent .. -1]
+        elif bytesSent == sock.sendBuffer.len:
+          sock.sendBuffer = ""
+        
+        if PAsyncSocket(h).handleWrite != nil:
+          PAsyncSocket(h).handleWrite(PAsyncSocket(h))
+      except EOS:
+        # Most likely the socket closed before the full buffer could be sent to it.
+        sock.close() # TODO: Provide a handleError for users?
     else:
       if PAsyncSocket(h).handleWrite != nil:
         PAsyncSocket(h).handleWrite(PAsyncSocket(h))