/// <summary> /// 连接服务器 /// </summary> /// <param name="serverName"></param> /// <param name="host"></param> public OpcResult Connect(string serverName, string host = "127.0.0.1") { OpcResult opcResult = OpcResult.ServerNoConnect; try { this.OpcServerName = serverName; this.Host = host; if (string.IsNullOrWhiteSpace(serverName) || string.IsNullOrWhiteSpace(host)) { if (!Equals(null, OnLogHappened)) { OnLogHappened(this, new OpcLogEventArgs("未指定服务器或主机名称")); } opcResult = OpcResult.E_FAIL; return(opcResult); } if (IsConnected) { if (!Equals(null, OnLogHappened)) { OnLogHappened(this, new OpcLogEventArgs("Opc服务器已经连接,host=" + host + ",serverName=" + serverName)); } opcResult = OpcResult.S_OK; return(opcResult); } var servers = OpcClientHelper.getOpcServers(host); if (!Equals(null, servers) && servers.Any(a => a.Name == serverName)) { opcServer = (Opc.Da.Server)servers.FirstOrDefault(a => a.Name == serverName); opcServer.Connect(); //服务器断开事件 opcServer.ServerShutdown += opcServer_ServerShutdown; IsConnected = true; if (!Equals(null, OnLogHappened)) { OnLogHappened(this, new OpcLogEventArgs("连接Opc服务器成功,host=" + host + ",serverName=" + serverName)); } //连接成功后开启守护进程 daemonTimer.Enabled = true; daemonTimer.Start(); opcResult = OpcResult.S_OK; } return(opcResult); } catch (Exception ex) { IsConnected = false; if (!Equals(null, OnErrorHappened)) { OnErrorHappened(this, new OpcErrorEventArgs(OpcResult.E_FAIL, "连接Opc服务器时出错:" + ex.Message, ex)); } opcResult = OpcResult.E_FAIL; return(opcResult); } }
private void intiOpcClientHelper() { opcClienthelper = new OpcClientHelper(); opcClienthelper.OnLogHappened += OpcClienthelper_OnLogHappened; opcClienthelper.OnErrorHappened += OpcClienthelper_OnErrorHappened; opcClienthelper.OnDataChanged += OpcClienthelper_OnDataChanged; //var servers1 = OpcHelper.OpcClientHelper.GetOpcServers(); //var servers2 = OpcHelper.OpcClientHelper.GetOpcServers("127.0.0.1"); //clienthelper.Connect(servers1.First()); }