alex
alex

Reputation: 1278

networkstream always empty!

hey I'm writing on an Server-Client program but when my client sends something, it never reaches my server!

I'm sending like this:

    public void Send(string s)  
    {  
        char[] chars = s.ToCharArray();  
        byte[] bytes = chars.CharToByte();  
        nstream.Write(bytes, 0, bytes.Length);  
        nstream.Flush();  
    }

and Receiving in a background thread like this

    void CheckIncoming(object dd)
    {
        RecievedDelegate d = (RecievedDelegate)dd;
        try
        {

            while (true)
            {
                List<byte> bytelist = new List<byte>();
                System.Threading.Thread.Sleep(1000);
                int ssss;
                ssss = nstream.ReadByte();
                if (ssss > 1)
                {
                    System.Diagnostics.Debugger.Break();
                }
                if (bytelist.Count != 0)
                {
                    d.Invoke(bytelist.ToArray());
                }
            }
        }
        catch (Exception exp)
        {
            MSGBOX("ERROR:\n" + exp.Message);
        }
    }

the ssss int is never > 1 whats happening here???

Upvotes: 2

Views: 1355

Answers (3)

Mark
Mark

Reputation: 345

NetworkStream.Flush() actually has no effect:

The Flush method implements the Stream..::.Flush method; however, because NetworkStream is not buffered, it has no affect [sic] on network streams. Calling the Flush method does not throw an exception

How much data is being sent?
If you don't send enough data it may remain buffered at the network level, until you close the stream or write more data.

See the TcpClient.NoDelay property for a way to disable this, if you are only going to be sending small chunks of data and require low latency.

Upvotes: 2

alex
alex

Reputation: 1278

well, Im creating a TcpClient, and use GetStream(); to get the NetworkStream

Upvotes: 0

mafu
mafu

Reputation: 32640

You should change the check of the return value to if (ssss >= 0).

ReadByte returns a value greater or equal 0 if it succeeds to read a byte (source).

To elaborate on Marc's comment: How is nstream created? Maybe there is an underlying class that does not flush.

Upvotes: 0

Related Questions