0

I am currently trying to make a little server, but I have encountered a problem, what I belive is a deadlock. And my question is how to actually avoid deadlock problem in C# Tcp? Let me show you something.

        public static void SendString (TcpClient klient, string message) {
        byte[] byteBuffer = Encoding.UTF8.GetBytes(message);
        NetworkStream netStream = klient.GetStream();
        netStream.Write(byteBuffer, 0, byteBuffer.Length);
        netStream.Write(new byte[] { separator }, 0, sizeof(byte));
        netStream.Flush();
    }

    public static string AcceptString (TcpClient klient) {
        List<int> buffer = new List<int>();
        NetworkStream stream = klient.GetStream();
        int readByte;
        while ((readByte = stream.ReadByte()) != 0)
            buffer.Add(readByte);

        return Encoding.UTF8.GetString(buffer.Select<int, byte>(b => (byte)b).ToArray(), 0, buffer.Count);
    }

Can deadlock occur when both sides try to call SendString() (on each other)? And if not, what actually causes deadlock? I mean I know what deadlock is (when both sides are waiting for action of the other side) but what it actually means in C# networking?

Valli3
  • 153
  • 2
  • 12
  • deadlock is deadlock. It is the same in all languages. http://stackoverflow.com/questions/8064296/is-deadlock-possible-when-locking-one-global-object-in-asp-net-mvc-application – Eser Sep 03 '15 at 19:10
  • It is not a deadlock, it is an invalid communication protocol. When two sides communicate, the way messgaes are formed, terminated and the exact sequence of messages is called a protocol. To come up with a valid protocol that doesn't lead to such issues, study some existing protocols like HTTP to get the idea. – Wiktor Zychla Sep 03 '15 at 19:10
  • 1
    What makes you think that? AcceptString will never return with this particular code because the connection is never closed by the sender. That's not a deadlock. – usr Sep 03 '15 at 20:30

1 Answers1

2

There is no deadlock in your case. At least I can't see any. Why should there be one?
Every computers can send any amount of data to another computer. The data will be stored in the target computer's network receive buffer, until some piece of software fetches it. In general, the data sending is not affected by the receipt of other data.

Tobias Knauss
  • 3,361
  • 1
  • 21
  • 45
  • Thanks! I though that this is deadlock because my server only accepts the first string and ignored others. – Valli3 Sep 05 '15 at 12:09