python socket on server code example
Example 1: python socket disconnect
import select
import socket
ip = '127.0.0.1'
port = 80
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.connect((ip, port))
while True:
try:
ready_to_read, ready_to_write, in_error = \
select.select([conn,], [conn,], [], 5)
except select.error:
conn.shutdown(2)
conn.close()
print('connection error')
break
if len(ready_to_read) > 0:
recv = conn.recv(2048)
print(f'received: {recv}')
if len(ready_to_write) > 0:
conn.send('some stuff')
Example 2: python socket
import socket
HOST = '127.0.0.1'
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)