Dec-11-2020, 02:08 PM
import socket from argparse import ArgumentParser TCP_IP = "127.0.0.1" TCP_PORT = 5005 BUFFER_SIZE = 1024 SMALL_BUFFER_SIZE = 20 MESSAGE = "HELLO WORLD" def client(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect((TCP_IP, TCP_PORT)) sock.send(MESSAGE.encode()) data = sock.recv(BUFFER_SIZE) def server(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.bind((TCP_IP, TCP_PORT)) sock.listen(1) conn, (client_ip, client_port) = sock.accept() print("Connection address:", client_ip) print("Connection port:", client_port) while True: data = conn.recv(SMALL_BUFFER_SIZE) if not data: break print("received data:", data.decode(errors="ignore")) conn.send(data) def get_args(): parser = ArgumentParser() parser.add_argument("type", choices=["server", "client"], help="kind of service") return parser.parse_args() if __name__ == "__main__": args = get_args() if args.type == "server": try: server() except KeyboardInterrupt: pass elif args.type == "client": client()
- You can use a context-manager.
socket()
supports it likeopen()
- Encode messages before you send
- Decode messages early
- There is the possibility of a
UnicodeDecodeError
.
- Additional trick with tuple unpacking:
one, (two, three) = (1, (2, 3))
- You can have both in the same code, if you're using functions. In Addition ArgumentParser makes nice command line tools.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!