Programming with Sockets
Let's modify our previous TCP client to send arbitrary data to any server.
The following is an example of an enhanced TCP client:
import socket
HOST = 'localhost'
PORT = 12345
BUFSIZ = 256
if __name__ == '__main__':
client_sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
host = input("Enter hostname [%s]: " %HOST) or HOST
port = input("Enter port [%s]: " %PORT) or PORT
sock_addr = (host, int(port))
client_sock.connect(sock_addr)
payload = 'GET TIME'
try:
while True:
client_sock.send(payload.encode('utf-8'))
data = client_sock.recv(BUFSIZ)
print(repr(data))
more = input("Want to send more data to server[y/n]
:")
if more.lower() == 'y':
payload = input("Enter payload: ")
else:
break
except KeyboardInterrupt:
print("Exited by user")
client_sock.close()
If you run the preceding TCP server in one console and the TCP client in another
console, you can see the following interaction between the client and server.
After running the TCP server script you will get the following output:
python 7_3_tcp_server.py
Server waiting for connection...
Client connected from: ('127.0.0.1', 59961)