Python tcp文件传输
时间: 2023-11-05 14:08:37 浏览: 112
TCP协议是一种可靠的传输协议,适合用于文件传输。下面是一个简单的 Python TCP 文件传输的代码示例:
服务端代码:
```python
import socket
HOST = '127.0.0.1'
PORT = 8888
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
print('Waiting for client connection...')
conn, addr = s.accept()
print(f'Connected by {addr}')
with open('received_file.txt', 'wb') as f:
while True:
data = conn.recv(1024)
if not data:
break
f.write(data)
print('File transfer completed')
conn.close()
if __name__ == '__main__':
main()
```
客户端代码:
```python
import socket
HOST = '127.0.0.1'
PORT = 8888
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
with open('file_to_send.txt', 'rb') as f:
while True:
data = f.read(1024)
if not data:
break
s.sendall(data)
print('File transfer completed')
s.close()
if __name__ == '__main__':
main()
```
在这个例子中,客户端将本地的 `file_to_send.txt` 文件发送给服务端,服务端接收文件并保存到本地的 `received_file.txt` 文件中。你可以根据自己的需求修改代码,比如修改文件名、路径等等。
阅读全文