Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
TCP Communicate...
#3
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 like open()
  • 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!
Reply


Messages In This Thread
TCP Communicate... - by ATARI_LIVE - Dec-11-2020, 09:17 AM
RE: TCP Communicate... - by ATARI_LIVE - Dec-11-2020, 11:53 AM
RE: TCP Communicate... - by DeaD_EyE - Dec-11-2020, 02:08 PM
RE: TCP Communicate... - by ATARI_LIVE - Dec-15-2020, 08:50 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  how virtual and host can communicate? looney99 0 2,121 Nov-28-2019, 09:08 PM
Last Post: looney99
  virtual host and real network communicate looney99 3 2,914 Nov-20-2019, 12:27 PM
Last Post: ChislaineWijdeven
  How I can communicate Virutal GNS3 topology and real network ? looney99 0 1,802 Nov-13-2019, 08:11 PM
Last Post: looney99
  how can i write programs that communicate between different computers? yasientrabih23 2 2,833 Jan-14-2019, 03:06 PM
Last Post: yasientrabih23
  How to best communicate with android phone from PC running Python script? Sol33t303 1 6,769 Aug-30-2018, 05:04 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020