Reputation: 135
I am new to sockets in c# and cannot see the problem in my code. I have a C++ app that sends a series of 8 messages when my C# application connects to its socket. I know that the c++ application works because it has been tested elsewhere.
This is my c# socket creation code
m_tcpESSClient = new TcpClient(AddressFamily.InterNetwork);
m_tcpESSClient.ReceiveBufferSize = 4096;
m_tcpESSClient.BeginConnect(
IPAddress.Parse("127.0.0.01"),
8082,
new AsyncCallback(ConnectCallback2),
m_tcpESSClient);
This is the connect callback
private void ConnectCallback2(IAsyncResult result)
{
m_tcpESSClient.EndConnect(result);
State state = new State();
state.buffer = new byte[m_tcpESSClient.ReceiveBufferSize];
state.offset = 0;
NetworkStream networkStream = m_tcpESSClient.GetStream();
networkStream.BeginRead(
state.buffer,
state.offset,
state.buffer.Length,
ReadCallback2,
state
);
}
and this is the read callback
private void ReadCallback2(IAsyncResult result)
{
NetworkStream networkStream = m_tcpESSClient.GetStream();
int byteCount = networkStream.EndRead(result);
State state = result.AsyncState as State;
state.offset += byteCount;
// Show message received on UI
Dispatcher.Invoke(() =>
{
ListBox.Items.Add("Received ");
});
state.offset = 0;
networkStream.BeginRead(
state.buffer,
state.offset,
state.buffer.Length,
ReadCallback2,
state);
The problem is that all messages sent by the c++ application are not received. Please can anyone see what is wrong with my socket code.
Upvotes: 0
Views: 132
Reputation: 63722
TCP doesn't have a concept of messages. TCP operates on streams.
This means that even though the C++ application might be issuing eight separate Write
calls, you might receive all of that data with a single Read
(or require multiple Read
s to read data written by a single Write
). The items you add to the list box have no relation to the amount of "messages" the C++ application has sent you.
To actually identify individual messages, you need to have a message-based protocol on top of TCP streams. You can't just rely on individual Read
s. In any case, you need to parse the data you receive over the socket.
Upvotes: 4