TCP读取SICK511传感器数据:运行 debug文件下的exe,tcp读取卡顿
时间:2023-11-20 09:37:01
最近写了一个TCP读取SICK511传感器数据程序,vs代码在环境中直接运行没有问题,但运行debug文件下的exe,tcp读卡顿。仔细检查程序,发现程序逻辑没有问题,折腾了很长时间;附上未修改的代码:
主程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication10
{
class Program
{
public static byte[] SICK_CMD_CONTINUE_MERSSURE = { 0x02, 0x73, 0x45, 0x4E, 0x20, 0x4C, 0x4D, 0x44, 0x73, 0x63, 0x61, 0x6E, 0x64, 0x61, 0x74, 0x61, 0x20, 0x31, 0x03 };
static void Main(string[] args)
{
Class1 cs = new Class1();
string temp = "";
while (true)
{
try
{
for (int i = 0; i < 400; i )
{ temp = temp " " cs.databuffer[i].ToString(); }
Console.WriteLine("帧数:" temp);
temp = "";
Console.WriteLine();
}
catch(Exception ex)
{
Console.WriteLine(ex.StackTrace.ToString());
}
}
}
}
}
tcp连接类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleApplication10
{
class Class1
{
public static byte[] SICK_CMD_CONTINUE_MERSSURE = { 0x02, 0x73, 0x45, 0x4E, 0x20, 0x4C, 0x4D, 0x44, 0x73, 0x63, 0x61, 0x6E, 0x64, 0x61, 0x74, 0x61, 0x20, 0x31, 0x03 };
public byte[] databuffer = new byte[400];
public string temp = "";
public TcpClient tc ;
NetworkStream st;
Thread a;
public Class1()
{
tc = new TcpClient("192.168.0.1", 2112);
tc.ReceiveTimeout = 1000;
st = tc.GetStream();
a = new Thread(new ThreadStart(func));
a.IsBackground = true;
a.Start();
// st.Write(SICK_CMD_CONTINUE_MERSSURE, 0, 19);
}
public void func()
{
st.Write(SICK_CMD_CONTINUE_MERSSURE, 0, SICK_CMD_CONTINUE_MERSSURE.Length);
st.Read(databuffer, 0, 19);
while (true)
{
Thread.Sleep(2);
st.Read(databuffer, 0, 400);
}
}
}
}
检查程序程序逻辑没有问题,考虑到传感器和电脑的速度匹配及响应时间,就试着增加延时,偶然间在获得网络数据流之后,加入延时10ms,解决问题;
tc = new TcpClient("192.168.0.1", 2112);
tc.ReceiveTimeout = 1000;
st = tc.GetStream();
Thread.Sleep(10);
从tcp获取数据流后,需要延迟