lidehua
lidehua

Reputation: 13

messages are concatenated together when received in c#-code-client(finished)

c#-client-code is used in unity3d to receive data from erlang-server-code,and different font weight is showed in GUI.Label. i send the data below one by one(i mean i send it six times,the first time i send 1 ): 1 22 333 4444 55555 666666. then bad things come :22 , 333 4444 are in the same line and the font-weight of 4444 is different.sometimes the program just died or crashed actually ,i just don't know how to manager the recvMsg Thread. ---------------->thanks

public static TcpClient client=new TcpClient("127.0.0.1",8889);
public   NetworkStream stream=client.GetStream();
void Start () {
    Thread recvMsg=new Thread(new ThreadStart(recvChatRequest));
    recvMsg.Start();
}
void recvChatRequest(){
    while (true) {
        recvChatRequest1();
    }
}
void recvChatRequest1(){
    byte[] recvData=new byte[256];
    int bytes=stream.Read(recvData,0,256);
    string responseData=string.Empty;
    responseData=System.Text.Encoding.UTF8.GetString(recvData,0,bytes);   
    string temp = "\n";
    temp += responseData;
    label_Info += temp;
}

Upvotes: 1

Views: 322

Answers (1)

tkowal
tkowal

Reputation: 9289

TCP is a streaming protocol. It means, that if you send data on one end and then try to receive on the other, all messages are concatenated together. That is why, you get a couple of them in one line.

You need to define your own protocol to tell the client, where the message starts and where it ends. The simplest solution is to add fixed length "size of the message" before sending actual data (for example two bytes). You start by reading 2 bytes from the stream, decode it as length of the next message (n) and then read the message itself by reading exactly n bytes from the stream.

Of course, you have to modify your Erlang client to send the message size before the message.

Another way is to use Erlang External Term Format. On the Erlang server, you can simply use term_to_binary and on the C# client, you can decode it.

There is a library, that supports encoding Erlang External Term Format in .NET, but I don't think, it will do the stream chopping for you.

Upvotes: 0

Related Questions