TCP处理传入数据的难度 [英] TCP handle incoming data difficulty

查看:95
本文介绍了TCP处理传入数据的难度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#线程来处理传入的TCP数据。



数据具有预定义的格式,例如



十六进制:A1 B1 01 03数据... 0C 0E



其中A1 B1是同步字节(总是相同)

列表03是消息长度

和0C 0E是两个尾随字节(总是相同的)

如果此数据总是在一个TCP中打包它现在处理数据有问题。



i'm using a C# thread to handle incoming TCP data.

The data has a predefined format, e.g.

Hex: A1 B1 01 03 data... 0C 0E

where A1 B1 are to sync byte (which are always the same)
List 03 is the message length
and 0C 0E are two trailing bytes (which are always the same)
if this data is always in one TCP Package it is now problem to handle the data.

while (connection.Available < 4)
{ 
}

before = connection.Available;
nStream.Read(Buffer_Sync_length, 0, 4);
after = connection.Available;


if ((Buffer_Sync_length[0] == 0xA1) && (Buffer_Sync_length[1] == 0xB1))
{
    int length = Buffer_Sync_length[3];

    while (connection.Available < (length + 2))
    { }

    nStream.Read(inBuffer, 0, length+2);

    Array.Clear(rec_Buffer, 0, inBuffer.Length);

    Array.Copy(Buffer_Sync_length, rec_Buffer, 4);
    Array.Copy(inBuffer, 0, rec_Buffer, 4, length);

    transmit(rec_Buffer);

    Array.Clear(Buffer_Sync_length, 0, Buffer_Sync_length.Length);
    Array.Clear(inBuffer, 0, inBuffer.Length);
    Array.Clear(rec_Buffer, 0, rec_Buffer.Length);
}



在线程中运行。



但有时数据会随机分成TCP包。然后缓冲区中的同步字节位置不同。



我想到了一个环形缓冲区,其中数据被写入并不断搜索同步字节。 />


实施它的最佳方法是什么?或者你有其他建议吗?



Greets,Andi


which runs in a thread.

But sometimes the data is splitted randomly into TCP packages. Then the sync byte position is different in the buffer.

I have thought about a ring buffer where the data is written to and constantly searched for the Sync bytes.

What is the best way to implement it? Or do you have other suggestions?

Greets, Andi

推荐答案

是的,你可以用一个循环缓冲区,但你也可以利用协议(轻轻提供数据的大小)来询问所需的字节。
Yes, you could use a circular buffer, however you could as well take advantage from the protocol (size of data is gently provided) for asking just the needed bytes.


这篇关于TCP处理传入数据的难度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆