最近老板要求搞一个实时读取人体信号并显示的模块,但小弟刚入门C#,目前遇到点问题,尝试了一些方法还是解决不了,求大佬帮忙解答。
下位机单片机作为服务器,采集信号后传送给PC端显示。但是可能由于数据量太过庞大,每次接收显示的数据只有一点点,不能一直传输。按老板的要求,至少需要采集几个小时的肌电信号。所以目前很懵逼,求解答~下面把代码贴上来
下位机单片机作为服务器,采集信号后传送给PC端显示。但是可能由于数据量太过庞大,每次接收显示的数据只有一点点,不能一直传输。按老板的要求,至少需要采集几个小时的肌电信号。所以目前很懵逼,求解答~下面把代码贴上来
private void timerByClient_Tick(object sender, EventArgs e)
{
try
{
lock (nsClient)
{
if (nsClient != null && nsClient.CanRead)
{
if (nsClient.DataAvailable)
{
BeginReadServerMsg(nsClient);
ShowDataStat();
}
}
}
}
catch (ObjectDisposedException ex)
{
MessageBox.Show("数据无法读取,流对象已被销毁或与服务端已断开连接!详细信息:" + ex.ToString());
}
}
delegate void UpdateData(byte[] byteData);//声明一个委托
//byte[] byteTemp;
/// <summary>
/// 读取来自服务器的数据
/// </summary>
/// <param name="nsClient"></param>
public void BeginReadServerMsg(NetworkStream nsClient)
{
byte[] byteTemp = new byte[1000]; //字节buffer
//锁定客户端网络工作流
lock (nsClient)
{
try
{
if (nsClient.CanRead && nsClient.DataAvailable)
{
//保存从流中读取的字节数
int readSize = 0;
//保存从流中读取的总字节数
int totalSize = 0;
nsClient.ReadTimeout = 100;
nsClient.WriteTimeout = 100;
//创建临时保存每次读取数据的流对象
MemoryStream ms = new MemoryStream();
while (nsClient.DataAvailable)
{
byte[] msgByte = new byte[819200];
readSize = nsClient.Read(msgByte, 0, 819200);
while (readSize == 0) //如果接收到的有效字节数为0 说明服务器已经关闭了。这时候就跳出循环了。
{
//如果为0重新读取
continue;
}
totalSize += readSize;
////写入临时流中用于一次性全部读取数据
ms.Write(msgByte, 0, readSize);
}
msgBytesByServer = new byte[totalSize];
byteTemp = new byte[totalSize]; //字节buffer
ms.Position = 0; ////将ms临时流中保存的数据全部读出
int readAllSize = ms.Read(msgBytesByServer, 0, totalSize);
while (readAllSize >= 18)
{
UpdateData Update = new UpdateData(DecodeData);
msgBytesByServer.CopyTo(byteTemp, 0);
//string msg=System.Text.Encoding.Default.GetString(byteTemp);
//lbsClient.Text = msg + "\n\r";
if (!((byteTemp[0] == 0x82) & (byteTemp[17] == 0xff)))
{
for (int i = 1; i < readAllSize; i++) msgBytesByServer[i - 1] = msgBytesByServer[i];
readAllSize--;
continue;
}
Invoke(Update, byteTemp);
for (int i = 18; i < readAllSize; i++) msgBytesByServer[i - 18] = msgBytesByServer[i];
readAllSize -= 18;
}
String serverMsg = Encoding.Default.GetString(msgBytesByServer, 0, msgBytesByServer.Length);
nsClient.Flush();
ms.Close();
}
}
catch (SocketException ex)
{
MessageBox.Show("读取来自服务器的数据发生异常,详细信息:" + ex.ToString());
}
}
}
但是我现在把定时器去掉之后,程序就会一直卡死在if (nsClient.CanRead && nsClient.DataAvailable)这个地方 ,dataailable一直返回null 这是为什么?
LIst<byte[]> a
while(true)
{
lock(a){
a.add( TCPCLient.Read...)
}
}然后在另一个线程中使用
循环取a 里的数据就行了