File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change @@ -1905,6 +1905,37 @@ is optional in pyscript):
19051905 print (resp.status)
19061906 print (resp.text())
19071907
1908+ Here's another example that creates a client connection to a TCP server and exchanges messages
1909+ in a manner that avoids event loop I/O by using ``asyncio.open_connection ``.
1910+
1911+ .. code :: python
1912+
1913+ import asyncio
1914+
1915+ Reader, Writer = None , None
1916+
1917+ @time_trigger (' startup' )
1918+ def do_client_connection ():
1919+ global Reader, Writer
1920+ Reader, Writer = asyncio.open_connection(' 127.0.0.1' , 8956 )
1921+
1922+ def client_send (message ):
1923+ if not Writer:
1924+ raise (" Client is not connected" )
1925+ Writer.write(message.encode())
1926+ Writer.drain()
1927+ return Reader.readline().decode()
1928+
1929+ This connects to the server (in this example at ``127.0.0.1:8956 ``) at startup, and then you can call
1930+ ``client_send() `` and it will send the message and return the reply.
1931+
1932+ This assumes the protocol is line-oriented; you could call ``Reader.read() `` instead if you want to
1933+ read bytes instead of expecting a newline with ``Reader.readline() ``.
1934+
1935+ To test the code above, you can create a server by running ``nc -l 8956 `` before you run the code.
1936+ When you call ``client_send("hello\n") `` you should see the ``hello `` printed by ``nc ``. Then
1937+ whatever you type back at ``nc `` will be returned by ``client_send() ``.
1938+
19081939Persistent State
19091940^^^^^^^^^^^^^^^^
19101941
You can’t perform that action at this time.
0 commit comments