C# Networking Issue

Hi,

I’ve created a Unity world that allows users to generate simple programs which are stored as local external files. The files can also individually be uploaded to an online server via a GUI interface using the inbuit Unity tools and a C# TCPClient.

So far I have the Unity client uploading program files to the online server working fine. My problem comes when I try to send a String back to the client from the server containing an acknowledgement message. For some reason after sending the file to the server Unity simply hangs/freezes up when trying to receive the acknowledgement String.

I need to send the response string on the same TCP connection that sent the program file (byte array). The code I’ve written is below. The Write function on the NetworkStream works fine if I take out the StreamReader, but Unity freezes if it is included.

public static string sendFile(string filepath) {

    String response = "";

    // Get the file
    Stream fileStream = File.OpenRead(filepath);

    byte[] buffer = new byte[fileStream.Length];
    fileStream.Read(buffer, 0, buffer.Length);

    try {

        // Create the connection
        TCPClient client = new TCPClient("127.0.0.1", 21000);

        NetworkStream stream = client.GetStream();

        // Send the file to the server
        stream.Write(buffer, 0, buffer.Length);
        stream.Flush();

        // Receive a single string response from the server
        if (stream.CanRead) {

            StreamReader input = new StreamReader(stream);
            inputString = input.ReadLine();

        }

        input.Close();
        stream.Close();
        client.Close();

    }

    catch (IOException e) {

        print ("Error: " + e);

    }

    // Return the response message string
    return inputString;

}

The online server the Unity script is connecting to is written in Java, (I’m actually a Java programmer so my C# is less than perfect). According to some logging on the server the file sent by the code above is being received and the response is being sent, but I believe Unity is hanging because for some reason it isn’t being recieved correctly at input.ReadLine().

I have also tried implementing the code above using a StreamWriter rather than writing directly from the NetworkStream itself and everything works perfectly. Unfortunately the StreamWriter class doesn’t have a method for sending a byte array, (only a char array).

If anybody has any idea why the code above isn’t working then please let me know. Alternatively, if you have a different solution that would allow me to send a file (byte array) and receive back a string message using the same TCPClient connection then please also feel free to mention it.

Regards,

midavi.

Hi,

Does anybody have any ideas about a solution to my problem or an alternative method I could use?

I’m getting rather desperate now.

Regards,

Midavi.