python中使用socket服务发送接收图像

python中使用socket服务发送接收图像的代码,可在服务器端中插入模型推理代码进行推理返回结果。

服务器端

python 复制代码
# -*-coding:utf-8-*-
import os.path
import socket
import struct


def deal_image(sock, addr):
    print('connection', addr)
    while True:
        # 计算文件信息大小
        fileinfo_size = struct.calcsize('128sq')
        # 接收文件信息buf
        buf = sock.recv(fileinfo_size)
        if buf:
            # 解包
            filename, filesize = struct.unpack('128sq', buf)
            fn = filename.decode().strip('\x00')
            new_filename = os.path.join('./', 'new_' + fn)
            recvd_size = 0
            # 保存图像
            fp = open(new_filename, 'wb')
            
            # 没看董
            while not recvd_size == filesize:
                if filesize - recvd_size > 1024:
                    data = sock.recv(1024)
                    recvd_size += len(data)
                else:
                    data = sock.recv(1024)
                    recvd_size = filesize
                # 写数据
                fp.write(data)
            # 关闭文件
            fp.close()
        # 关闭服务
        sock.close()
        break

# 建立连接
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(5)

while True:
    # 接收连接的地址
    c, addr = s.accept()
    str = 'hello,world,' + str(addr)
    # 发送连接消息,以信息流的方式发送
    c.send(str.encode(encoding='utf-8'))
    print(addr)
    # 处理接收的图像数据
    deal_image(c, addr)
    c.close()

客户端

python 复制代码
# -*-coding:utf-8-*-
import os.path
import socket
import struct

# 初始化客户端建立通信
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect((host, port))

#接收消息
data = s.recv(1024).decode(encoding='utf-8')
print(data)

#发送图片文件头信息
filepath = r'./123.jpg'
fhead = struct.pack(b'123sq', bytes(os.path.basename(filepath).encode(encoding='utf-8')), os.stat(filepath).st_size)
s.send(fhead)

#发送图像
fp = open(filepath, 'rb')
while True:
    data = fp.read(1024)
    if not data:
        print('send over')
        break
    s.send(data)
# 关闭连接
s.close()
相关推荐
笑稀了的野生俊2 小时前
在服务器中下载 HuggingFace 模型:终极指南
linux·服务器·python·bash·gpu算力
Naiva2 小时前
【小技巧】Python+PyCharm IDE 配置解释器出错,环境配置不完整或不兼容。(小智AI、MCP、聚合数据、实时新闻查询、NBA赛事查询)
ide·python·pycharm
路来了2 小时前
Python小工具之PDF合并
开发语言·windows·python
蓝婷儿2 小时前
Python 机器学习核心入门与实战进阶 Day 3 - 决策树 & 随机森林模型实战
人工智能·python·机器学习
AntBlack3 小时前
拖了五个月 ,不当韭菜体验版算是正式发布了
前端·后端·python
.30-06Springfield3 小时前
决策树(Decision tree)算法详解(ID3、C4.5、CART)
人工智能·python·算法·决策树·机器学习
我不是哆啦A梦3 小时前
破解风电运维“百模大战”困局,机械版ChatGPT诞生?
运维·人工智能·python·算法·chatgpt
WJ.Polar3 小时前
Python数据容器-list和tuple
开发语言·python
qq_229644113 小时前
LucidShape 2024.09 最新
python
花好月圆春祺夏安5 小时前
基于odoo17的设计模式详解---装饰模式
数据库·python·设计模式