2

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()

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, so simple yet I have been like 6 hours trying to figure it out. Thank you very much for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.