Modbus TCP多线程通信

Modbus Slave作为服务器,VS程序作为客户端,使用Socket定义TCP客户端,进行多路连接

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    ModbusTcpConnect();   //建立Tcp连接
}
/// <summary>
/// 建立MobusTCP连接
/// </summary>
private void ModbusTcpConnect()
{
    List<string> subnetList = (List<string>)cmbList.ItemsSource;    //获取子网列表
    int subnetCount = subnetList.Count;                           //获取子网数量
    //int subnetCount = 40;
    string[] address = new string[subnetCount];
    string[] port = new string[subnetCount];
    connectStatus = new bool[subnetCount];                     //实例化
    for (int i = 0; i < subnetCount; i++)                      //获取ip地址
    {
        address[i] = subnetList[i].Split(":")[0];
    }
    for (int i = 0; i < subnetCount; i++)                      //获取端口号
    {
        port[i] = subnetList[i].Split(":")[1];
    }
    //依次连接40个通道
    for (int i = 0; i < subnetCount; i++)
    {
        string[] arr = address[i].Split('.');                  //将ip地址按.进行分割
        if (arr.Length == 4)
        {
            foreach (string item in arr)
            {
                int ipRange = int.Parse(item);
                if (ipRange < 0 || ipRange > 255) { return; }  //ip地址不合法
            }
        }
        if (int.Parse(port[i]) < 0) { return; }                //端口号小于0,不合法
        //多线程进行TCP客户端连接
        string[] connectThreadParams = new string[4];  //存储线程传递的多个参数
        connectThreadParams[0] = address[i];   //第一个参数为ip地址
        connectThreadParams[1] = port[i];      //第二个参数为端口号
        connectThreadParams[2] = i.ToString(); //第三个参数为第几个

        Thread connectThread = new Thread(new ParameterizedThreadStart(ClientConnect)); //客户端连接线程
        Thread.Sleep(50);
        connectThread.Start(connectThreadParams);             //开启后台线程
    }
}

/// <summary>
/// 进行客户端的连接
/// </summary>
/// <param name="obj"></param>
private void ClientConnect(object obj)
{
    string[] connectThreadParams = (string[])obj;
    int clientNum = Convert.ToInt32(connectThreadParams[2]);  //求出当前是第几个连接
    modTcpClient = new ModbusTcpClientHelper(2 * 1024);    //重新new一个ModbusTCP客户端
    modTcpClient.Start(connectThreadParams[0], connectThreadParams[1],clientNum);   //建立TCP连接
    counter = clientNum; //记录当前客户端编号

    Thread thread = new Thread(new ParameterizedThreadStart(SendMsg));   //开启线程向主站发送消息
    thread.Start(modTcpClient);

    Thread isconnectThread = new Thread(new ParameterizedThreadStart(IsClientConnect));
    isconnectThread.Start(modTcpClient);
    modTcpClientList.Add(modTcpClient);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值