socket发送多个文件
时间: 2023-07-31 20:11:33 浏览: 35
如果你需要在客户端和服务器之间发送多个文件,可以考虑使用多线程或者多进程同时发送多个文件,以提高传输效率。以下是一个简单的示例代码,可以发送多个文件:
服务端代码:
```python
import socket
import os
def send_file(conn, file_path):
with open(file_path, 'rb') as f:
data = f.read()
conn.sendall(data)
def handle_client(conn):
files_to_send = ['file1.txt', 'file2.txt', 'file3.txt']
for file_path in files_to_send:
if os.path.exists(file_path):
send_file(conn, file_path)
def main():
host = '127.0.0.1'
port = 5555
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(1)
print(f'Server listening on {host}:{port}...')
while True:
conn, addr = server.accept()
print(f'Connected by {addr}')
handle_client(conn)
conn.close()
if __name__ == '__main__':
main()
```
客户端代码:
```python
import socket
import os
def receive_file(conn, file_name):
with open(file_name, 'wb') as f:
while True:
data = conn.recv(1024)
if not data:
break
f.write(data)
def main():
host = '127.0.0.1'
port = 5555
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
print(f'Connected to {host}:{port}')
files_to_receive = ['file1.txt', 'file2.txt', 'file3.txt']
for file_name in files_to_receive:
receive_file(client, file_name)
client.close()
if __name__ == '__main__':
main()
```
在这个示例中,服务端将要发送的文件名存储在一个列表中,然后在处理客户端请求时,依次将文件发送给客户端。客户端在接收到连接后,依次接收服务端发送的每个文件。注意,在接收文件时,我们需要使用一个循环来不断接收数据,直到数据接收完毕。