我要用C#做一个数据采集系统的上位机,TCP连接,但现在的问题是下位机传的太快,每秒10万数据,一个数据4字节,我看了下我的上位机一分钟才接4000数据,还丢数
我要用C#做一个数据采集系统的上位机,TCP连接,但现在的问题是下位机传的太快,每秒10万数据,一个数据4字节,我看了下我的上位机一分钟才接4000数据,还丢数。
所以,我想问一下,有什么方法能够提高上位机的接收速度和保证接收数据完整
下位机传来四个字节代表一个数据,前三个字节是要处理的数据,最后一个字节是板号及通道号
我现在已经把数据采集和处理分到两个线程中了,但速度没有丝毫提升,丢数问题没有解决
/// <summary>
/// 下位机信息接收方法
/// </summary>
/// <param name="obj"></param>
private void reciveMsg(object obj)
{
Socket client = obj as Socket;
while (true)
{
byte[] FourB = new byte[4];
try
{
byte[] buffer = new byte[BytesCounts];
int length = client.Receive(buffer);
if(length !=0)
lenQueue.Enqueue(length);
myqueue.Enqueue(buffer);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
IPEndPoint point = client.RemoteEndPoint as IPEndPoint;
label2.Text = (point.ToString() + "断开连接。。。");
break;
}
}
}
/// <summary>
/// 下位机信息处理方法
/// </summary>
/// <param name="obj"></param>
private void DataProcessing(object obj)
{
Socket client = obj as Socket;
while (true)
{
byte[] FourB = new byte[4];
try
{
byte[] bufferOut = new byte[BytesCounts];
if (myqueue.Count != 0)
{
bufferOut = myqueue.Dequeue() as byte[];
int myLength = Convert.ToInt16(lenQueue.Dequeue());
string res = Encoding.UTF8.GetString(bufferOut, 0, bufferOut.Length);
for (int i = 0; i <= myLength- 4; i = i + 4)
{
if ((bufferOut[i] & 0x80) != 0x80) //判断是否是负数,如果是负数else处理
{
FourB[3] = 0x00;
FourB[2] = bufferOut[i];
FourB[1] = bufferOut[i + 1];
FourB[0] = bufferOut[i + 2];
}
else
{
FourB[3] = 0xff;
FourB[2] = bufferOut[i];
FourB[1] = bufferOut[i + 1];
FourB[0] = bufferOut[i + 2];
}
//得到的4字节数据处理为要显示的数据
int temp = BitConverter.ToInt32(FourB, 0);
double temp2 = Convert.ToDouble(temp);
double SCdata = (temp2 / 8388608) * 12.5;
//板号判断,通道号判断存入
switch (bufferOut[i + 3] & 0x38)
{
case (0x08):
{
int tongdaoName = bufferOut[i + 3] & 0x07;
if (tongdaoName != 0)
{
double[] tempArr = new double[3] { SCdata, 1, tongdaoName };
tempQueue.Enqueue(tempArr);
}
break;
}
case (0x10):
{
int tongdaoName = bufferOut[i + 3] & 0x07;
if (tongdaoName != 0)
{
double[] tempArr = new double[3] { SCdata, 2, tongdaoName };
tempQueue.Enqueue(tempArr);
}
break;
}
case (0x18):
{
int tongdaoName = bufferOut[i + 3] & 0x07;
if (tongdaoName != 0)
{
double[] tempArr = new double[3] { SCdata, 3, tongdaoName };
tempQueue.Enqueue(tempArr);
}
break;
}
case (0x20):
{
int tongdaoName = bufferOut[i + 3] & 0x07;
if (tongdaoName != 0)
{
double[] tempArr = new double[3] { SCdata, 4, tongdaoName };
tempQueue.Enqueue(tempArr);
}
break;
}
}
//Array.Clear(buffer, 0, buffer.Length);
label2.Text = ("接收到的消息:" + res);
}
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
IPEndPoint point = client.RemoteEndPoint as IPEndPoint;
label2.Text = (point.ToString() + "断开连接。。。");
break;
}
}
}