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()
相关推荐
喵手34 分钟前
Python爬虫实战:基于ETag/Last-Modified的智能条件请求与流量优化!
爬虫·python·爬虫实战·零基础python爬虫教学·etag/last·modified·智能条件请求与流量优化
MediaTea35 分钟前
Python:比较协议
运维·服务器·开发语言·网络·python
sg_knight1 小时前
对象池模式(Object Pool)
python·设计模式·object pool·对象池模式
240291003371 小时前
自编码器(AE)与变分自编码器(VAE)-- 认识篇
python·神经网络·机器学习
郝学胜-神的一滴1 小时前
Python中的“==“与“is“:深入解析与Vibe Coding时代的优化实践
开发语言·数据结构·c++·python·算法
一个处女座的程序猿O(∩_∩)O2 小时前
Python多重继承详解
开发语言·python
Loo国昌2 小时前
【AI应用开发实战】04_混合检索器:BM25+向量+可靠度融合实战
人工智能·后端·python·自然语言处理
belldeep2 小时前
python:用 Flask 3 , mistune 2 实现指定目录下 Md 文件的渲染
python·flask·markdown·mistune
52Hz1182 小时前
力扣33.搜索旋转排序数组、153.寻找排序数组中的最小值
python·算法·leetcode