zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    关于Java常见的误解
    Java程序设计概述
    是结束,更是开始!
    从零开始单排学设计模式「简单工厂设计模式」黑铁 III
    某神秘公司 RESTful、共用接口、前后端分离、接口约定的实践
    这40张图送给单身程序员,情人节请一笑而过!
    科技圈晒开工福利!2019一起定个小目标!
    IDEA一定要懂的32条快捷键
    假期结束了,我相信未来会更好!
    有一种痛,叫 “今年没有年终奖”!!!
  • 原文地址:https://www.cnblogs.com/lizhongren/p/12574677.html
Copyright © 2011-2022 走看看