Modbus Slave作为服务器,VS程序作为客户端,使用Socket定义TCP客户端,进行多路连接
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ModbusTcpConnect();
}
private void ModbusTcpConnect()
{
List<string> subnetList = (List<string>)cmbList.ItemsSource;
int subnetCount = subnetList.Count;
string[] address = new string[subnetCount];
string[] port = new string[subnetCount];
connectStatus = new bool[subnetCount];
for (int i = 0; i < subnetCount; i++)
{
address[i] = subnetList[i].Split(":")[0];
}
for (int i = 0; i < subnetCount; i++)
{
port[i] = subnetList[i].Split(":")[1];
}
for (int i = 0; i < subnetCount; i++)
{
string[] arr = address[i].Split('.');
if (arr.Length == 4)
{
foreach (string item in arr)
{
int ipRange = int.Parse(item);
if (ipRange < 0 || ipRange > 255) { return; }
}
}
if (int.Parse(port[i]) < 0) { return; }
string[] connectThreadParams = new string[4];
connectThreadParams[0] = address[i];
connectThreadParams[1] = port[i];
connectThreadParams[2] = i.ToString();
Thread connectThread = new Thread(new ParameterizedThreadStart(ClientConnect));
Thread.Sleep(50);
connectThread.Start(connectThreadParams);
}
}
private void ClientConnect(object obj)
{
string[] connectThreadParams = (string[])obj;
int clientNum = Convert.ToInt32(connectThreadParams[2]);
modTcpClient = new ModbusTcpClientHelper(2 * 1024);
modTcpClient.Start(connectThreadParams[0], connectThreadParams[1],clientNum);
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);
}