• Python基于TCP与UDP协议实现Socket通信


    TCP协议

    server.py

    from socket import socket
    
    tcp_server = socket()
    tcp_server.bind(('127.0.0.1', 9000))
    tcp_server.listen()
    
    conn, addr = tcp_server.accept()
    
    msg = conn.recv(1024)
    print(msg)
    conn.send(b'hello from server')
    
    conn.close()
    tcp_server.close()

    client.py

    from socket import socket
    
    tcp_client = socket()
    tcp_client.connect(('127.0.0.1', 9000))
    
    tcp_client.send(b'hello from client')
    msg = tcp_client.recv(1024)
    print(msg)
    
    tcp_client.close()

     

    UDP协议

    server.py

    from socket import socket, SOCK_DGRAM
    
    udp_server = socket(type=SOCK_DGRAM)
    udp_server.bind(('127.0.0.1', 9000))
    
    msg, client_addr = udp_server.recvfrom(1024)
    print(msg)
    udp_server.sendto(b'hello from server', client_addr)
    
    udp_server.close()

    client.py

    from socket import socket, SOCK_DGRAM
    
    udp_client = socket(type=socket.SOCK_DGRAM)
    
    udp_client.sendto(b'hello from client', ('127.0.0.1', 9000))
    msg = udp_client.recv(1024)
    print(msg)
    
    udp_client.close()

     

    socketserver实现TCP协议可并发的server端

    from socketserver import BaseRequestHandler, ThreadingTCPServer
    
    class MyServer(BaseRequestHandler):
        def handle(self):  # 自动触发handle方法,self.request 相当于 conn
            msg = self.request.recv(1024).decode('utf-8')
            self.request.send('收到'.encode('utf-8'))
    
    server = ThreadingTCPServer(('127.0.0.1',9000), MyServer)
    server.serve_forever()

    struct模块解决TCP协议的粘包现象

    • 先发送报头

      • 报头长度为4个字节,内容是即将发送的报文的字节长度

      • struct模块中的pack方法能够把所有的数字都固定的转换成4字节

    • 再发送报文

    server.py

    import socket
    import struct
    
    sk = socket.socket()
    sk.bind(('127.0.0.1', 9000))
    sk.listen()
    
    conn, _ = sk.accept()
    
    byte_len1 = conn.recv(4)
    size1 = struct.unpack('i', byte_len1)[0]
    msg1 = conn.recv(size1)
    print(msg1)
    
    byte_len2 = conn.recv(4)
    size2 = struct.unpack('i', byte_len2)[0]
    msg2 = conn.recv(size2)
    print(msg2)
    
    conn.close()
    sk.close()

    client.py

    import socket
    import struct
    
    sk = socket.socket()
    sk.connect(('127.0.0.1', 9000))
    
    msg1 = b'hello'
    byte_len1 = struct.pack('i', len(msg1))
    sk.send(byte_len1)
    sk.send(msg1)
    
    msg2 = b'world'
    byte_len2 = struct.pack('i', len(msg2))
    sk.send(byte_len2)
    sk.send(msg2)
    
    sk.close()
  • 相关阅读:
    EYES组——软件体系结构上机规划
    淘宝软件架构分析分工
    淘宝网系统架构分析以及数据库架构简介
    关于编译器与解释器的区别
    Web前端之高斯模糊图片记
    解决JS浮点数(小数)计算加减乘除的BUG
    JS滚轮事件(mousewheel/DOMMouseScroll)了解
    阻止事件冒泡
    记一次编码相关问题
    细说Form(表单)
  • 原文地址:https://www.cnblogs.com/lizhongren/p/12574677.html
Copyright © 2020-2023  润新知