基于 Python 的服务端和客户端互相连续发送图片的示例代码

零妖贰捌 分享 496

以下是基于 Python 的服务端和客户端互相连续发送图片的示例代码:

服务端代码:

import socket
import os
# 创建 TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 10000)
print('Starting up on %s port %s' % server_address)
sock.bind(server_address)
# 监听客户端请求
sock.listen(1)
while True:
print('Waiting for a connection...')
# 接受客户端的连接请求
connection, client_address = sock.accept()
print('Connection from', client_address)
while True:
# 接收客户端消息
data = connection.recv(1024)
if not data:
# 如果客户端断开连接,则跳出循环
print(client_address, "disconnected")
break
filename = data.decode('utf-8')
filesize = os.path.getsize(filename)
print('Receiving file:', filename)
# 发送文件大小
connection.sendall(str(filesize).encode('utf-8'))
# 发送文件内容
with open(filename, 'rb') as f:
data = f.read(1024)
while data:
connection.sendall(data)
data = f.read(1024)
print('File transfer completed.')
# 关闭连接
connection.close()

客户端代码:

import socket
import os
# 创建 TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 10000)
sock.connect(server_address)
while True:
# 输入文件名
filename = input('Enter filename (blank to exit): ')
if not filename:
# 如果输入为空,则断开连接
break
# 发送文件名
sock.sendall(filename.encode('utf-8'))
# 接收服务端发送的文件大小
data = sock.recv(1024)
filesize = int(data.decode('utf-8'))
if filesize == 0:
print('File not found!')
continue
print('Receiving file size:', filesize)
# 接收文件内容
with open(filename, 'wb') as f:
received_size = 0
while received_size < filesize:
data = sock.recv(1024)
received_size += len(data)
f.write(data)
print('File transfer completed.')
# 断开连接
sock.close()

这个代码在客户端每次发送完一张图片后,可继续输入另一张图片的文件名进行传输。服务端也是一样的,每次接收完一张图片后,可继续监听客户端的请求。您可以将代码中的文件名替换成您自己的图片文件名以进行测试。

回复

我来回复
  • 暂无回复内容

公众号
公众号
创建WIFI码
创建WIFI码
在线客服
分享本页
返回顶部