python工具-udp-tcp-client-server-demo

python工具-udp-tcp-client-server-demo

  • server
    • tcp-server: python xxx.py -type tcp -ip "127.0.0.1" -port 1234
    • udp-server: python xxx.py -type udp -ip "127.0.0.1" -port 1234
  • client
    • python xxx.py -type udp -ip "127.0.0.1" -port 1111
    • python xxx.py -type tcp -ip "127.0.0.1" -port 1111

server-demo

python 复制代码
import datetime
import socket
import select
import argparse

def udp_listen(local_ip, local_port):
    buffer_size  = 1024
    bytes_to_send         = str.encode("Hello UDP Client")
    # Create a datagram socket
    with socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) as sock:
        # Bind to address and ip
        sock.bind((local_ip, local_port))

        print(f"UDP server up and listening, {local_ip}:{local_port}")
        # Listen for incoming datagrams
        while(True):
            recv_data = sock.recvfrom(buffer_size)
            message = recv_data[0]
            address = recv_data[1]
            print("==========================")
            print(datetime.datetime.now())    
            print(f"Message from Client:{message}")
            print(f"Client IP Address:{address}")

            # Sending a reply to client
            sock.sendto(bytes_to_send, address)

def tcp_listen(ip, port):
  # create socket
  with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((ip, port))
    print("[+] Listening on {0}:{1}".format(ip, port))
    sock.listen(5)  # permit to access
    sock.setblocking(False)

    poll = select.poll()
    poll.register(sock, select.POLLIN)  # 注册 listen socket 到 pull 中
    fd_to_socket = {}

    try:
        while True:
            ready = poll.poll()
            if not ready:
                break

            for fd, _ in ready:
                if fd == sock.fileno():
                    sub_sock, client_address = sock.accept()
                    print("==========================")
                    print("Accepted from", client_address)

                    fd_to_socket[sub_sock.fileno()] = sub_sock
                    poll.register(sub_sock, select.POLLIN)  # 注册 accept socket 到 pull 中
                else:
                    sub_sock = fd_to_socket[fd]
                    raw_data = sub_sock.recv(1024)

                    if not raw_data:
                        print("Closed connection to", sub_sock.getpeername())
                        poll.unregister(sub_sock)
                        sub_sock.close()
                        break

                    sub_sock.sendall(f"hello {client_address}".encode())
                    print("Reveived {} from {}".format(raw_data.decode(), sub_sock.getpeername()))
    except KeyboardInterrupt:
        print("EXIT")
    except Exception as e:
        print(e)
    poll.unregister(sock)
    


# python xxx.py -type udp -ip "127.0.0.1" -port 1234
# python xxx.py -type tcp -ip "127.0.0.1" -port 1234
if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.description='please enter correct para'
    parser.add_argument("-type", "--type", help="tcp or udp", type=str, default="udp")
    parser.add_argument("-ip", "--ip", help="listen ip", type=str, default="127.0.0.1")
    parser.add_argument("-port", "--port", help="listen port",  type=int, default=1111)
    try:
        args = parser.parse_args()
        if args.type == "udp":
            udp_listen(args.ip, args.port)
        elif args.type == "tcp":
            tcp_listen(args.ip, args.port)
    except Exception as e:
        print(e)
    

client-demo

python 复制代码
import socket
import datetime
import argparse

def udp_send(server_ip, server_port, bytes_to_send):
    server_address   = (server_ip, server_port)
    recv_buf_size          = 1024

    # Create a UDP socket at client side
    client = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
    client.settimeout(3)
    # Send to server using created UDP socket
    try:
        print(datetime.datetime.now())
        print(f"send {bytes_to_send} to {server_ip}:{server_port}")
        # 可以通过 udp_client.bind 绑定本地发送的ip和port
        client.sendto(bytes_to_send, server_address)
        print(f"local_addr: {client.getsockname()}")
        recv_data = client.recvfrom(recv_buf_size)
        print(f"message from server {recv_data[0]}")
    except Exception as e:
        print(f"connect {server_address} fail. reasion:{e}")

def tcp_send(server_ip, server_port, bytes_to_send):
    server_address   = (server_ip, server_port)
    recv_buf_size          = 1024

    # Create a UDP socket at client side
    client = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
    client.settimeout(3)
    # Send to server using created UDP socket
    try:
        print(datetime.datetime.now())
        print(f"send {bytes_to_send} to {server_ip}:{server_port}")
        # 可以通过 udp_client.bind 绑定本地发送的ip和port
        client.connect(server_address)
        client.sendall(bytes_to_send)
        print(f"local_addr: {client.getsockname()}")
        recv_data = client.recv(recv_buf_size)
        print(f"message from server {recv_data}")
    except Exception as e:
        print(f"connect {server_address} fail. reasion:{e}")


# python xxx.py -type udp -ip "127.0.0.1" -port 1111
# python xxx.py -type tcp -ip "127.0.0.1" -port 1111
if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.description='please enter correct para'
    parser.add_argument("-type", "--type", help="tcp or udp", type=str, default="udp")
    parser.add_argument("-ip", "--ip", help="listen ip", type=str, default="127.0.0.1")
    parser.add_argument("-port", "--port", help="listen port",  type=int, default=1111)
    try:
        args = parser.parse_args()
        if args.type == "udp":
            udp_send(args.ip, args.port, "hello server".encode())
        elif args.type == "tcp":
            tcp_send(args.ip, args.port, "hello server".encode())
    except Exception as e:
        print(e)
相关推荐
豌豆花下猫几秒前
Python 潮流周刊#78:async/await 是糟糕的设计(摘要)
后端·python·ai
只因在人海中多看了你一眼4 分钟前
python语言基础
开发语言·python
小技与小术11 分钟前
数据结构之树与二叉树
开发语言·数据结构·python
hummhumm38 分钟前
第 25 章 - Golang 项目结构
java·开发语言·前端·后端·python·elasticsearch·golang
杜小满42 分钟前
周志华深度森林deep forest(deep-forest)最新可安装教程,仅需在pycharm中完成,超简单安装教程
python·随机森林·pycharm·集成学习
databook2 小时前
『玩转Streamlit』--布局与容器组件
python·机器学习·数据分析
nuclear20112 小时前
使用Python 在Excel中创建和取消数据分组 - 详解
python·excel数据分组·创建excel分组·excel分类汇总·excel嵌套分组·excel大纲级别·取消excel分组
Lucky小小吴3 小时前
有关django、python版本、sqlite3版本冲突问题
python·django·sqlite
GIS 数据栈3 小时前
每日一书 《基于ArcGIS的Python编程秘笈》
开发语言·python·arcgis
爱分享的码瑞哥3 小时前
Python爬虫中的IP封禁问题及其解决方案
爬虫·python·tcp/ip