【问题标题】:Send image from C# to Python through TCP not working通过 TCP 将图像从 C# 发送到 Python 不起作用
【发布时间】:2015-12-17 13:40:06
【问题描述】:

问题

我正在尝试通过 TCP 发送图像 (PNG) 并将其保存在服务器上,客户端用 C# 编写,服务器用 Python 编写。我已经测试过服务器可以使用 Python 编写的程序,但是当我尝试使用 C# 执行相同操作时,它只会发送一个部分并卡住。

我尝试打印服务器正在接收的数据,但似乎只收到了前 1024 个字节,然后在尝试接收更多字节时卡住了。

注意:我已将主机更改为“localhost”,端口更改为通用端口,但我实际上是在非本地的虚拟专用服务器上进行测试,它实际上是从托管公司租用的。

代码如下:

Python 客户端(有效):

import socket

s = socket.socket()
host = "localhost"
port = 12345
s.connect((host, port))

file = open("image.png", "rb")
imgData = file.read()

s.send(imgData)

s.close()

C# 客户端(这不起作用):

TcpClient tcp = new TcpClient("localhost", 12345);

NetworkStream stream = tcp.GetStream();

byte[] image = File.ReadAllBytes("image.png");
stream.Write(image, 0, image.Length);

Python 服务器

#!/usr/bin/python

import socket
import os
import io
import os.path

def Main():
    s = socket.socket()
    host = socket.gethostname()
    port = 12345
    s.bind((host, port))

    s.listen(1)
    print("Waiting for a connection...")

    c, addr = s.accept()
    print("Connection from: " + str(addr))

    if os.path.isfile("image.png"):
        os.remove("image.png")

    file = open("image.png", "w+b")
    while True:
        data = c.recv(1024)
        if not data:
            break
        file.write(data)
        print(str(list(data)))

    print("Done.")
    c.close()
    s.close()

if __name__ == "__main__":
    Main()

【问题讨论】:

    标签: c# python image networking tcp


    【解决方案1】:

    您需要close TCP 流,以便发送所有数据。

    using (var tcp = new TcpClient("localhost", 12345))
    {
        byte[] image = File.ReadAllBytes("image.png");
        tcp.GetStream().Write(image, 0, image.Length);
    }
    

    using 语句将在代码块运行后通过Dispose 方法关闭TcpClient。这将关闭并重置 tcp 流。

    【讨论】:

    • 哇,这么简单,但我花了 6 个小时才弄明白。非常感谢您的帮助。
    猜你喜欢
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 2014-09-03
    • 2015-03-03
    • 2013-07-21
    • 1970-01-01
    相关资源
    最近更新 更多