TCP messages not being sent

Started by
2 comments, last by hplus0603 11 years, 8 months ago

Hi

I am currently working on a project that involves a server and multiple clients that can connect to it and request data. Im sending messages (strings) from the client to the server and vice versa (never between clients), but sometimes they dont get sent but are stuck until I try to send it again, and then both messages are sent at the same time. At first this seemed easy to solve: the packets are automatically stored until there is enough data to send out in order to save bandwith (aka Nagle algorithm), so setting tcpclient.NoDelay = true should do the trick, but it didnt. I've tried to solve this for days now, but can't get any progress on it.

Im using a BinaryWriter for sending data, and also tried the tcpclient.Client.Send(byte[]) method with the same results.

public Client()

{

this.tcpClient = new TcpClient();

this.tcpClient.NoDelay = true;

this.outgoingMessages = new List<string>();

}





/// <summary>

/// Write pending messages to the server.

/// </summary>

private void Write() //This is running in a thread

{

while (true)

{

lock (this.outgoingMessages)

{

if (this.binaryWriter != null && this.outgoingMessages.Count > 0)

{

this.binaryWriter.Write(this.outgoingMessages[0]);

this.binaryWriter.Flush();

this.outgoingMessages.RemoveAt(0);

}

}

Thread.Sleep(33);

}

}


Hopefully someone knows an answer to this smile.png
Advertisement
How does the server handle reading data? Is it non blocking? It is possible that the server is blocking while waiting for data from a particular client, and all the other clients then block as the server's receiving buffers for their connection fills.
This is how I receive incoming data (also running in a thread)


/// <summary>
/// Read the incoming messages from the server.
/// </summary>
private void Read()
{
while (true)
{
this.CheckConnection();
if (this.isConnected && this.tcpClient.Available > 0)
{
string message = this.binaryReader.ReadString();

//Processing the message
//...
}
Thread.Sleep(33);
}
}
You are not guaranteed that an entire string is available, just because some bytes are available.

Typically, on TCP, you will prefix each message (string, in this case) with a length value, and you'll receive data into a buffer. When there is enough data in the buffer to cover both the length value, and all the data that that length value says should be there, you decode that message and remove from the buffer.
enum Bool { True, False, FileNotFound };

This topic is closed to new replies.

Advertisement