问题
I have build a app that can connect to my server. Everything is running smoothly, but I have a problem when the server send message to client simultaneously. Such as when the server sends 2 messages in row. The client just receives the first one. Is there possible to get more than one message in row?
Here is my part of code for client:
TcpClient clientSocket;
public string IPS= "###.###.###.###";
public int SocketS = ####;
public void ConnectingToServer()
{
clientSocket= new TcpClient();
clientSocket.Connect(IPS, SocketS);
if (clientSocket.Connected)
{
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes();
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
}
// Function for send data to server.
public void SendDataToServer(string StrSend)
{
if (clientSocket.Connected)
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(StrSend);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
}
// Function for receive data from server (I put this in looping).
public void getMessage()
{
if (clientSocket != null)
{
if (clientSocket.Connected)
{
if (serverStream.DataAvailable)
{
int buffSize = 0;
buffSize = clientSocket.ReceiveBufferSize;
byte[] inStream = new byte[buffSize];
serverStream.Read(inStream, 0, buffSize);
string StrReceive= System.Text.Encoding.ASCII.GetString(inStream);
}
}
}
}
回答1:
The send/receive functions of socket do not guarantee that all the data you provided will be sent/received at one call. The functions return actual number of sent/received bytes. In your case, you must not ignore the result of the serverStream.Read(...) method call.
That is why application-level protocol should be designed to exchange the things (you call it "messages").
There are many approaches to design the protocol, but let's consider the following "message" protocol as an example:
----------------------------------------------------
| Number of string bytes | String bytes in UTF-8 |
----------------------------------------------------
| 1 byte | 2 - ... bytes |
----------------------------------------------------
Sending the "message": the string should be converted to UTF-8 (for example) representation and sent it with the byte length of the byte representation (as described above).
Receiving the message: receive the data to memory buffer. The process of extracting the "message" is opposite to the sending ones. Of course, you can receive more than one "message" at once, so process the buffer thoroughly.
Example
I have just written a small article with code example.
来源:https://stackoverflow.com/questions/14725215/c-sharp-tcp-client-cant-get-more-than-1-message-in-row