python:如何通过udp同时从多个客户端接收二进制数据?

n7taea2i  于 2021-08-20  发布在  Java
关注(0)|答案(0)|浏览(289)

我有一个简单的udp客户机-服务器程序,它有两个文件-sender.py和listener.py。sender.py只是在listener.py接收二进制数据并将其保存在计算机上时发送文件。这很好,多个客户端可以连接到服务器,一次发送一个文件。问题是服务器不能同时从多个客户端接收数据。当我试图同时从多个客户端发送文件时,数据只从一个客户端处理。
您能告诉我如何设置udp服务器来同时存储来自多个客户端的二进制数据吗?
listener.py

import os

buf = 1024

host = input('enter ip address: ')
port = int(input('enter port number: '))

address = (host, port)

# create a UDP socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# allow multiple sockets to use the same PORT number

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# Bind the ip and port number

s.bind((host, port))

def listen():
    while True:
        file = None
        try:
            data, addr = s.recvfrom(buf)
            print(f'server received data from: {addr}')

            file = open('test.wav', 'wb')

            while data:
                file.write(data)
                s.settimeout(2)
                data, addr = s.recvfrom(buf)
        except socket.timeout:
            if file is not None:
                file.close()

listen()

sender.py

buf = 1024

host = input('enter ip address: ')
port = int(input('enter port number: '))

address = (host, port)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, 0))
s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

def send_file():
    file_name = input('insert path to a file: ')
    f = open(file_name, "rb")
    data = f.read(buf)

    print("sending data...")
    while data:
        if s.sendto(data, address):
            data = f.read(buf)

    f.close()

send_file()

while True:
    if input('Exit? (y/n)') == 'y':
        s.close()
        break
    send_file()

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题