I am having some trouble figuring out why I am only receiving one reply from a server application running on my computer(LocalHost). I do not have the source for this server application but it is a java application. Messages that is sent is a xml structure and have to end with a EoT tag.
The communication:
- Client connect to sever.
- Client sends message to server.
- Server sends message recived to client.
- Client sends message to server.
- Server sends a End of Transmission character.
- Client sends message to server.
- Server sends a End of Transmission character.
This is how my client connect, send and receive:
public bool ConnectSocket(string server, int port)
{
System.Net.IPHostEntry hostEntry = null;
try
{
// Get host related information.
hostEntry = System.Net.Dns.GetHostEntry(server);
}
catch (System.Exception ex)
{
return false;
}
// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
// an exception that occurs when the host IP Address is not compatible with the address family
// (typical in the IPv6 case).
foreach (System.Net.IPAddress address in hostEntry.AddressList)
{
System.Net.IPEndPoint ipe = new System.Net.IPEndPoint(address, port);
System.Net.Sockets.Socket tempSocket = new System.Net.Sockets.Socket(ipe.AddressFamily, System.Net.Sockets.SocketType.Stream,
System.Net.Sockets.ProtocolType.Tcp);
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
m_pSocket = tempSocket;
m_pSocket.NoDelay = true;
return true;
}
else
continue;
}
return false;
}
}
public void Send(string message)
{
message += (char)4;//We add end of transmission character
m_pSocket.Send(m_Encoding.GetBytes(message.ToCharArray()));
}
private void Recive()
{
byte[] tByte = new byte[1024];
m_pSocket.Receive(tByte);
string recivemessage = (m_Encoding.GetString(tByte));
}
Your
Receivecode looks very wrong; you should never assume that packets arrive in the same constructions that the server sends messages – TCP is just a stream. So: you must catch the return fromReceive, to see how many bytes you received. It could be part of one message, an entire message, multiple entire messages, or the last half of one message and the first half of the next. Normally, you need some kind of “framing” decision, which could mean “messages split by LF characters”, or could mean “the length of each message is prefixed by network-byte-order integer, 4 bytes”. This usually means you need to buffer until you have a full frame, and worry about spare data at the end of the buffer that is part of the next frame. Key bits to add, though:In particular, with text formats, you cannot start decoding until you are sure you have an entire message buffered, because a multi-byte character might be split between two messages.
There may well also be problems in your receive loop, but you don’t show that (nothing calls
Receive), so we can’t comment.