C# 网口demo

csharp 复制代码
bool _testStatus = false;
private void btnOpsStart_Click(object sender, EventArgs e)
{
    int delay = Convert.ToInt32(txtdelay.Text.Trim());
    txtView.Clear();
    txtView.AppendText("******************************************开始烤机********************************" + "\r\n");
    Task.Factory.StartNew(() =>
    {
        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        _testStatus = true;
        try
        {
            client.Connect(new IPEndPoint(IPAddress.Parse(txtIp.Text), Convert.ToInt32(txtPort.Text)));
            SetOpsBtnEnable(false);
            while (_testStatus)
            {
                //端口1做主循环,其他三个端口做子循环
                for (int i = 0; i <= 4; i++)
                {
                    for (int j = 0; j <= 4; j++)
                    {
                        for (int k = 0; k <= 4; k++)
                        {
                            for (int l = 0; l <= 4; l++)
                            {
                                if (!_testStatus)
                                {
                                    return;
                                }
                                string send = $"Configure:WorkChannelAll {i} {j} {k} {l}";
                                ShowMsg(send);
                                client.Send(Encoding.ASCII.GetBytes(send + "\n"));
                                Thread.Sleep(delay);
                                string select = $"Configure:WorkChannelAll?";
                                ShowMsg(select);
                                client.Send(Encoding.ASCII.GetBytes(select + "\n"));
                                //Thread.Sleep(20);
                                string result = string.Empty;
                                string errMsg = string.Empty;
                                ReadResult(client, ref result, ref errMsg);
                                ShowMsg(result);
                                result = result.Replace("\n","");
                                string[] resArr = result.Split(' ');
                                if (i!=Convert.ToInt32(resArr[0]))
                                {
                                    _testStatus = false;
                                    ShowMsgBox($"配置{send}和查询{result}不一致!");
                                }
                                if (j != Convert.ToInt32(resArr[1]))
                                {
                                    _testStatus = false;
                                    ShowMsgBox($"配置{send}和查询{result}不一致!");
                                }
                                if (k != Convert.ToInt32(resArr[2]))
                                {
                                    _testStatus = false;
                                    ShowMsgBox($"配置{send}和查询{result}不一致!");
                                }
                                if (l != Convert.ToInt32(resArr[3]))
                                {
                                    _testStatus = false;
                                    ShowMsgBox($"配置{send}和查询{result}不一致!");
                                }
                                //Thread.Sleep(100);
                            }
                        }
                    }
                    
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
            _testStatus = false;
        }
        finally
        {
            client.Shutdown(SocketShutdown.Both);
        }
    }).ContinueWith((task) =>
    {
        SetOpsBtnEnable(true);
    });
}
csharp 复制代码
/// <summary>
/// 读取网口结果 结果是按/n或/r结尾的
/// </summary>
/// <param name="result"></param>
/// <param name="errMsg"></param>
/// <returns></returns>
public bool ReadResult(Socket client, ref string result, ref string errMsg)
{
    try
    {
        lock (_lockWr)
        {
            DateTime triggerStart = DateTime.Now;
            bool pass = true;
            List<byte> listbyte = new List<byte>();
            while (pass)
            {
                DateTime triggerEnd = DateTime.Now;
                double collecTime = (triggerEnd - triggerStart).TotalMilliseconds;
                if (collecTime >= 10000)
                {
                    //MessageBox.Show("Read time over-limit");
                    errMsg = "Read time over-limit";
                    return false;
                }
                int relength = client.Available;
                byte[] rebyte = new byte[relength];
                client.Receive(rebyte);
                foreach (byte a in rebyte)
                {
                    listbyte.Add(a);
                }
                if (listbyte.Count != 0)
                {
                    if (listbyte.Last() == 10 || listbyte.Last() == 13)
                    {
                        pass = false;
                    }
                }
                //Thread.Sleep(5);
            }
            byte[] readbyt1 = new byte[listbyte.Count];
            for (int a = 0; a < listbyte.Count; a++)
            {
                readbyt1[a] = listbyte[a];
            }
            result = System.Text.ASCIIEncoding.Default.GetString(readbyt1);
            return true;
        }
    }
    catch (Exception ex)
    {
        errMsg = ex.ToString();
        return false;
    }
}
csharp 复制代码
private void btnOpsStop_Click(object sender, EventArgs e)
 {
     _testStatus = false;
     //SetOpsBtnEnable(true);
 }

 public void ShowMsg(string msg)
 {
     this.Invoke(new Action(() =>
     {
         if (txtView.Lines.Length > 6000)
         {
             txtView.Clear();
         }
         DateTime date = DateTime.Now;
         this.txtView.AppendText($@"{date.ToString("yyyy-MM-dd HH:mm:ss")} {msg} {"\r\n"}");
     }));
 }

 public void SetOpsBtnEnable(bool isEnable)
 {
     this.Invoke(new Action(() =>
     {
         btnOpsStart.Enabled = isEnable;
         btnSameChannelStart.Enabled = isEnable;
         btnOpsStop.Enabled = !isEnable;
     }));
 }

 public void ShowMsgBox(string ErrMsg)
 {
     this.Invoke(new Action(() =>
     {
         MessageBox.Show(ErrMsg);
     }));
 }
相关推荐
lilv668 分钟前
python中用xlrd、xlwt读取和写入Excel中的日期值
开发语言·python·excel
阿巴~阿巴~1 小时前
构造函数:C++对象初始化的核心机制
开发语言·c++
蒋星熠2 小时前
QT项目 -仿QQ音乐的音乐播放器(第五节)
开发语言·qt
叫我:松哥2 小时前
基于Python的实习僧招聘数据采集与可视化分析,使用matplotlib进行可视化
开发语言·数据库·python·课程设计·matplotlib·文本挖掘
澡点睡觉3 小时前
golang的面向对象编程,struct的使用
开发语言·爬虫·golang
王维志3 小时前
⏱ TimeSpan:C#时间间隔结构
前端·后端·c#·.net
绿炮火3 小时前
【MATLAB】(十)符号运算
开发语言·matlab
俄城杜小帅4 小时前
QML与C++交互的方式
开发语言·c++·交互
Asu52025 小时前
思途spring学习0807
java·开发语言·spring boot·学习