Difference between revisions of "Socket code in levels of complexity"
From MyWiki
(4 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
− | Complexity 1, very simple | + | '''Complexity 1''', very simple. Connect using "telnet localhost 9988", send a few characters and then press <enter><br> |
− | The characters are echoed back and the connection is | + | The characters are echoed back and the connection is closed<br> |
<source lang="python"> | <source lang="python"> | ||
#!/usr/bin/python3 | #!/usr/bin/python3 | ||
Line 17: | Line 17: | ||
conn.close() | conn.close() | ||
+ | </source> | ||
+ | '''Complexity 2''', we can add logging<br> | ||
+ | <source lang="python"> | ||
+ | #!/usr/bin/python3 | ||
+ | |||
+ | import socket | ||
+ | import logging | ||
+ | import sys | ||
+ | |||
+ | |||
+ | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||
+ | logging.basicConfig(format='%(levelname)s - %(asctime)s: %(message)s',datefmt='%H:%M:%S', level=logging.DEBUG) | ||
+ | s.bind(("localhost", 9988)) | ||
+ | s.listen(1) | ||
+ | |||
+ | while True: | ||
+ | conn, addr = s.accept() | ||
+ | data = conn.recv(1024) | ||
+ | #print(data) | ||
+ | logging.info(data.decode("utf-8")) | ||
+ | conn.sendall(data) | ||
+ | conn.close() | ||
</source> | </source> |
Latest revision as of 15:34, 20 January 2022
Complexity 1, very simple. Connect using "telnet localhost 9988", send a few characters and then press <enter>
The characters are echoed back and the connection is closed
#!/usr/bin/python3 import socket import sys s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("localhost", 9988)) s.listen(1) while True: conn, addr = s.accept() data = conn.recv(1024) conn.sendall(data) conn.close()
Complexity 2, we can add logging
#!/usr/bin/python3 import socket import logging import sys s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) logging.basicConfig(format='%(levelname)s - %(asctime)s: %(message)s',datefmt='%H:%M:%S', level=logging.DEBUG) s.bind(("localhost", 9988)) s.listen(1) while True: conn, addr = s.accept() data = conn.recv(1024) #print(data) logging.info(data.decode("utf-8")) conn.sendall(data) conn.close()