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?

3
  • deadlock is deadlock. It is the same in all languages. stackoverflow.com/questions/8064296/… Commented Sep 3, 2015 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. Commented Sep 3, 2015 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. Commented Sep 3, 2015 at 20:30

1 Answer 1

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.

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

1 Comment

Thanks! I though that this is deadlock because my server only accepts the first string and ignored others.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.