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

零妖贰捌 分享 581

以下是基于 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)
# 接收客户端消息
data = connection.recv(1024)
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)
# 发送文件名
filename = 'picture.jpg'
sock.sendall(filename.encode('utf-8'))
# 接收服务端发送的文件大小
data = sock.recv(1024)
filesize = int(data.decode('utf-8'))
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码
在线客服
分享本页
返回顶部