Difference between revisions of "Socket code in levels of complexity"

From MyWiki
Jump to: navigation, search
 
(One intermediate revision by the same user not shown)
Line 18: Line 18:
  
 
</source>
 
</source>
Complexity 2, we can add logging<br>
+
'''Complexity 2''', we can add logging<br>
 
<source lang="python">
 
<source lang="python">
#!/usr/bin/python3 -u
+
#!/usr/bin/python3  
 
   
 
   
 
import socket
 
import socket

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()