使用多线程编程技术,编写一个文件上传程序,使之可以同时接收多个客户端上传文件
时间: 2024-11-12 19:42:20 浏览: 3
使用多线程编程技术创建一个文件上传程序,可以让它有效地处理并发请求,让多个客户端能够并行上传文件而不会互相阻塞。下面是一个简单的Python示例,使用`threading`库来实现在服务器端:
```python
import socket
import threading
class FileUploader(threading.Thread):
def __init__(self, client_socket, filename):
threading.Thread.__init__(self)
self.client_socket = client_socket
self.filename = filename
def run(self):
print(f"New connection from {self.client_address[0]}")
with open(self.filename, 'wb') as file:
data = b''
while True:
chunk = self.client_socket.recv(4096) # 每次接收4K数据
if not chunk:
break # 如果接收到空数据,表示客户端已关闭连接
data += chunk
file.write(chunk)
self.client_socket.close()
print(f"{self.filename} uploaded by {self.client_address[0]}")
def server_start(host, port):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(5)
while True:
client_socket, client_address = server.accept()
filename = f"upload_{client_address[0]}_{client_address[1]}"
upload_thread = FileUploader(client_socket, filename)
upload_thread.start()
if __name__ == "__main__":
server_start('localhost', 8000)
```
这个示例中,`FileUploader`类代表每个上传任务的线程。当有新客户端连接时,会创建一个新的`FileUploader`实例,并开始运行。每个线程负责接收来自单个客户端的数据,直到文件上传完成。
阅读全文