• 【python】socket


    UDP

    udp_server.py

    from datetime import datetime
    import socket
    
    server_address = ('localhost', 6789)
    max_size = 4096
    
    print('Starting the server at', datetime.now())
    print('Waiting for a client to call.')
    server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server.bind(server_address)
    
    data, client = server.recvfrom(max_size)
    
    print('At', datetime.now(), client, 'said', data)
    server.sendto(b'Are you talking to me?', client)
    server.close()

    udp_client.py

    import socket
    from datetime import datetime
    
    server_address = ('localhost', 6789)
    max_size = 4096
    
    print('Starting the client at', datetime.now())
    client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    client.sendto(b'Hey!', server_address)
    data, server = client.recvfrom(max_size)
    print('At', datetime.now(), server, 'said', data)
    client.close()

    TCP

    tcp_server.py

    from datetime import datetime
    import socket
    
    address = ('localhost', 6789)
    max_size = 1000
    
    print('Starting the server at', datetime.now())
    print('Waiting for a client to call.')
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(address)
    server.listen(5) # 最多和5个客户端连接,超过5个就会拒绝
    
    client, addr = server.accept()
    data = client.recv(max_size)
    
    print('At', datetime.now(), client, 'said', data)
    client.sendall(b'Are you talking to me?')
    client.close()
    server.close()

    tcp_client.py

    import socket
    from datetime import datetime
    
    address = ('localhost', 6789)
    max_size = 1000
    
    print('Starting the client at', datetime.now())
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(address)
    client.sendall(b'Hey!')
    data = client.recv(max_size)
    print('At', datetime.now(), 'someone replied', data)
    client.close()
  • 相关阅读:
    Spring Boot 2.x基础教程:加密配置中的敏感信息
    Spring Boot 2.x基础教程:Swagger静态文档的生成
    Spring Boot 2.x基础教程:使用Swagger2构建强大的API文档
    线性代数相关
    CF1738 E. Balance Addicts
    初赛
    排列&答案最优
    2022牛客OI赛前集训营提高组(第一场)
    10/3 模拟赛 | 牛客 2020 tg1
    Codeforces Round #821 (Div. 2) D E
  • 原文地址:https://www.cnblogs.com/jzm17173/p/5802542.html
Copyright © 2020-2023  润新知