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

From MyWiki
Jump to: navigation, search
Line 1: Line 1:
Complexity 1, very simple, connect using telnet localhost 9988, send a few characters and then press <enter><br>
+
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 disconnected<br>
+
The characters are echoed back and the connection is closed<br>
 
<source lang="python">
 
<source lang="python">
 
#!/usr/bin/python3
 
#!/usr/bin/python3

Revision as of 10:14, 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()