使用python的socket库写一个用于传输txt文件的程序
时间: 2024-05-14 07:14:55 浏览: 71
以下是一个用Python Socket库编写的简单程序,用于从客户端向服务器传输txt文件。
服务端代码:
``` python
import socket
# 创建一个TCP/IP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定套接字到端口
server_address = ('localhost', 8888)
print('Starting up on %s port %s' % server_address)
server_socket.bind(server_address)
# 监听来自客户端的连接
server_socket.listen(1)
while True:
print('Waiting for a connection...')
connection, client_address = server_socket.accept()
try:
print('Connection from', client_address)
# 接收文件名
file_name = connection.recv(1024).decode()
print('Received file name:', file_name)
# 打开文件并从客户端接收数据
with open(file_name, 'wb') as f:
while True:
data = connection.recv(1024)
if not data:
break
f.write(data)
print('File received successfully!')
finally:
# 清理连接
connection.close()
print('Connection closed')
```
客户端代码:
``` python
import socket
# 创建一个TCP/IP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接到服务端的端口
server_address = ('localhost', 8888)
client_socket.connect(server_address)
# 发送文件名
file_name = 'test.txt'
client_socket.sendall(file_name.encode())
# 发送文件数据
with open(file_name, 'rb') as f:
while True:
data = f.read(1024)
if not data:
break
client_socket.sendall(data)
print('File sent successfully!')
# 关闭套接字
client_socket.close()
```
这个简单的程序仅适用于传输小文件,如果需要传输大文件,则需要对代码进行优化。
阅读全文