mcmacker4
mcmacker4

Reputation: 53

Send image from C# to Python through TCP not working

The Problem

I am trying to send an image (PNG) over TCP and save it on the server the client is written in C# and the server in Python. I have tested that the server works with a Python written program but when I try to do the same using C# it just sends one part and gets stuck.

I have tried to print the data that is being received by the server and it seems like only the first 1024 bytes are received and then it gets stuck trying to receive more.

Note: I have changed the host with "localhost" and the port with a generic one but i am actually testing this on a virtual private server that is not local, it is in fact rented from a hosting company.

Here is the code:

Python Client (this works):

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# Client (this doesn't work):

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

NetworkStream stream = tcp.GetStream();

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

Python Server

#!/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()

Upvotes: 2

Views: 2690

Answers (1)

Richard Schneider
Richard Schneider

Reputation: 35477

You need to close the TCP stream so that all data is sent.

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

The using statement will close the TcpClient via the Dispose method after the code block is run. This will close and reset the tcp stream.

Upvotes: 2

Related Questions