继续,帮我写一下tcp协议传输文件的服务器端的程序
时间: 2023-06-06 11:05:35 浏览: 81
好的,我来帮您写一个TCP协议传输文件的服务器端程序,以下是示例代码:
```python
import socket
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机名和端口号
host = socket.gethostname()
port = 8888
# 绑定主机和端口号
server_socket.bind((host, port))
# 设置最大连接数
server_socket.listen(5)
# 等待客户端连接
client_socket, addr = server_socket.accept()
print(f"客户端 {addr} 已连接")
# 接收文件名
file_name = client_socket.recv(1024).decode()
print(f"正在接收文件 {file_name}")
# 打开文件并发送
with open(file_name, "rb") as f:
data = f.read(1024)
while data:
client_socket.send(data)
data = f.read(1024)
print("文件传输完成")
# 关闭socket连接
client_socket.close()
server_socket.close()
```
使用示例:
```python
import socket
# 创建socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取主机名和端口号
host = socket.gethostname()
port = 8888
# 连接到服务器
client_socket.connect((host, port))
# 发送文件名
file_name = "example.txt"
client_socket.send(file_name.encode())
# 接收文件
with open(f"received_{file_name}", "wb") as f:
data = client_socket.recv(1024)
while data:
f.write(data)
data = client_socket.recv(1024)
print("文件接收完成")
# 关闭socket连接
client_socket.close()
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)