简体   繁体   English

如何使用套接字发送多个图像文件?

[英]How to send multiple image files using sockets?

The below code only sends the first image file. 以下代码仅发送第一个图像文件。 How can I send multiple images? 如何发送多张图像?

Server side code: 服务器端代码:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 12345))
bind to ('', port)
s.listen(10)
c, addr = s.accept()
print('{} connected.'.format(addr))

m = c.recv(1024)
m1 = c.recv(1024)
f = open(r"C:\python voice\haha3.jpg", "wb")
f1 = open(r"C:\python voice\haha4.jpg", "wb")
data = None
data1 = None

while True:
    data = m
    data1 = m1
    if m:
        while m:
            m = c.recv(1024)
            data += m
        else:
            break
    if m1:
        while m1:
            m1 = c.recv(1024)
            data1 += m1
        else:
            break

f.write(data)
f.close()
f1.write(data1)
f1.close()

print("Done receiving")

Client side code: 客户端代码:

import socket
import os

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1",12345))
f = open(r"C:\python voice\image.jpg", "rb")
l = os.path.getsize(r"C:\python voice\image.jpg")
m = f.read(l)
s.send(m)
f.close()
print("Done sending...")

f1 = open(r"C:\python voice\image1.jpg", "rb")
l1 = os.path.getsize(r"C:\python voice\image1.jpg")
m1 = f1.read(l1)
s.send(m1)
f1.close()
print("Done sending...")

You use a plain TCP protocol. 您使用普通的TCP协议。

This is a transport protocol. 这是一种传输协议。 It deals with generic streams of bytes. 它处理通用的字节流。

You have to use or invent an application protocol that knows what files are. 您必须使用或发明知道什么文件的应用程序协议。

Example: before sending the file send a header describing how many files will follow and their sizes in bytes. 示例:在发送文件之前,发送一个标头,描述将跟随多少文件及其大小(以字节为单位)。 With that info you can reconstruct the files from the stream 通过该信息,您可以从流中重建文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM