/// <summary>
/// 根据IP地址获取DNS主机名
/// </summary>

/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
try
{
IPHostEntry iPHostEntry = Dns.GetHostEntry(textBox1.Text);
textBox2.Text = iPHostEntry.HostName;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
/// <summary>
/// 获取OPC服务器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
try
{
if (textBox2.Text != "")
{
kepServer = new OPCServer();
//获取指定DNS主机名上的OPC服务器
object serverList = kepServer.GetOPCServers(textBox2.Text);
comboBox1.Items.Clear();
foreach (string serverName in (Array)serverList)
{
if (!comboBox1.Items.Contains(serverName))
{
comboBox1.Items.Add(serverName);
}
}
}
else
{
MessageBox.Show("请先获取DNS主机名");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
/// <summary>
/// 连接OPC服务器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
bool connFlag= ConnectServer(comboBox1.Text,textBox2.Text);
if(connFlag==true)
{
button3.Text = "已连接OPC";
}
GetOPC_Info();
kepBrowser = kepServer.CreateBrowser();
CreateKepBrowser(kepBrowser);
CreateGroup();
}
/// <summary>
/// 连接OPC服务器,并返回是否连接成功
/// </summary>
/// <param name="serverName"></param>
/// <param name="ServerNode"></param>
/// <returns></returns>
public bool ConnectServer(string serverName,String ServerNode)
{
try
{
kepServer.Connect(serverName, ServerNode);
//判断OPC服务器的连接状态
if (kepServer.ServerState == (int)OPCServerState.OPCRunning)
{
toolStripStatusLabel1.Text = "已连接到服务器:" + kepServer.ServerName + " ";
return true;
}
else
{
toolStripStatusLabel1.Text= "状态:" + kepServer.ServerState.ToString() + " ";
return false;
}
}
catch
{
return false;
}
}
4、完整代码较长,如需要完整代码可先关注并留言,然后私信我发送“OPCDA”即可自动回复,如果能帮助到你,感谢你的关注订阅,可以第一时间接收后续更新。