/// <summary> /// UDP重新连接方法 /// </summary> private void TcpAutoReconnect() { while (true) { Thread.Sleep(1000); //假如属性提示未连接,则UDP重连线程挂起 if (!IsConnected) { Auto_UdpReconnect.WaitOne(); } //假如属性提示已连接但实际上连接已断开,尝试重连 //else if (IsConnected && !IsSocketConnected()) else if (IsConnected && !IsConnected_Socket) { string temp = string.Format("UDP主机地址:{0},端口号:{1}", ServerIp, ServerPort); //UDP连接的主机地址与端口 LastErrorMessage = "UDP连接意外断开,正在尝试重连。" + temp; FileClient.WriteFailureInfo(LastErrorMessage); try { BaseClient.Close(); BaseClient = HoldLocalPort ? new UdpClient(LocalEndPoint) : new UdpClient(); BaseClient.Connect(ServerIp, ServerPort); SetName(); //重连次数+1,同时调用事件委托 ReconnTimer++; if (ReconnTimerChanged != null) { ReconnTimerChanged.BeginInvoke(Name, ReconnTimer, null, null); } if (Connected != null) { Connected.BeginInvoke(Name, new EventArgs(), null, null); } //NetStream = BaseClient.GetStream(); if (AutoReceive) { BaseClient.BeginReceive(new AsyncCallback(ReceiveCallBack), this); } //NetStream.BeginRead(Buffer, 0, Buffer.Length, new AsyncCallback(TcpCallBack), this); //IsSocketConnected(); FileClient.WriteFailureInfo("UDP重新连接成功。" + temp); } //假如出现异常,将错误信息写入日志并进入下一次循环 catch (Exception e) { LastErrorMessage = string.Format("UDP重新连接失败:{0}。", e.Message) + temp; FileClient.WriteExceptionInfo(e, LastErrorMessage, false); continue; //TODO: 是否抛出异常? //throw; //假如不需要抛出异常,注释此句 } } } }
/// <summary> /// 关闭连接 /// </summary> /// <returns>假如关闭成功,返回1,否则返回0</returns> public int Close() { string _class = MethodBase.GetCurrentMethod().ReflectedType.FullName; //命名空间+类名 string _method = string.Format("Int32 {0}", new StackTrace().GetFrame(0).GetMethod().Name); //方法名称 //假如未连接,返回错误信息 if (!this.IsConnected) { LastErrorMessage = "并未与任何主机建立连接,无需断开连接!"; FileClient.WriteFailureInfo(new string[] { LastErrorMessage, string.Format("类名称:{0},方法名称:{1}", _class, _method) }); return(0); } LastErrorMessage = string.Empty; int result = 1; if (ConnType == ConnTypes.TCP) { try { result = this.TcpClient.Close(); ServerIp = this.TcpClient.ServerIp; ServerPort = this.TcpClient.ServerPort; IsConnected = this.TcpClient.IsConnected; } catch (Exception) { LastErrorMessage = this.TcpClient.LastErrorMessage; throw; } } //TODO 编写其它连接方式的断开方法 else { //try //{ // result = BaseUdpClient.Close(); // ServerIp = BaseUdpClient.ServerIp; // ServerPort = BaseUdpClient.ServerPort; // IsConnected = BaseUdpClient.IsConnected; //} //catch (Exception) { LastErrorMessage = BaseUdpClient.LastErrorMessage; throw; } } ConnType = result == 1 ? ConnTypes.UNCONNECTED : ConnType; return(result); }
/// <summary> /// TCP客户端以byte数组或16进制格式字符串发送数据 /// </summary> /// <param name="data_origin">待发送数据,byte数组或16进制格式字符串</param> /// <param name="errorMessage">返回的错误信息,假如未报错则为空</param> /// <returns>返回发送结果</returns> public bool SendData(object data_origin, out string errorMessage) { errorMessage = string.Empty; if (!IsConnected || !IsSocketConnected()) { errorMessage = string.Format("TCP服务端{0}未连接", Name); if (logging) { FileClient.WriteFailureInfo(errorMessage); } return(false); } byte[] data; string typeName = data_origin.GetType().Name; if (typeName == "Byte[]") { data = (byte[])data_origin; } else if (typeName == "String") { data = HexHelper.HexString2Bytes((string)data_origin); } else { errorMessage = string.Format("数据格式不正确({0}),无法向TCP服务端{1}发送数据", typeName, Name); FileClient.WriteFailureInfo(errorMessage); return(false); } try { NetStream.Write(data, 0, data.Length); } catch (Exception ex) { errorMessage = string.Format("向TCP服务端{0}发送数据失败 {1}", Name, ex.Message); FileClient.WriteExceptionInfo(ex, errorMessage, false); //MessageBox.Show(selClient.Name + ":" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } return(true); }
/// <summary> /// UDP客户端以byte数组或16进制格式字符串发送数据 /// </summary> /// <param name="data_origin">待发送数据,byte数组或16进制格式字符串</param> /// <param name="endPoint">远程IP终结点</param> /// <param name="errorMessage">返回的错误信息,假如未报错则为空</param> /// <returns>返回发送结果</returns> public bool SendData(object data_origin, IPEndPoint endPoint, out string errorMessage) { errorMessage = string.Empty; //if (!IsConnected || !IsSocketConnected()) //{ // errorMessage = string.Format("UDP服务端{0}未连接", Name); // if (logging) // FileClient.WriteFailureInfo(errorMessage); // return false; //} byte[] data; string typeName = data_origin.GetType().Name; if (typeName == "Byte[]") { data = (byte[])data_origin; } else if (typeName == "String") { data = HexHelper.HexString2Bytes((string)data_origin); } else { errorMessage = string.Format("数据格式不正确({0}),无法向UDP服务端{1}发送数据", typeName, Name); FileClient.WriteFailureInfo(errorMessage); return(false); } try { BaseClient.Send(data, data.Length, endPoint); } catch (Exception ex) { errorMessage = string.Format("向UDP服务端{0}发送数据失败 {1}", Name, ex.Message); FileClient.WriteExceptionInfo(ex, errorMessage, false); return(false); } return(true); }
/// <summary> /// 通讯连接 /// </summary> /// <param name="serverIp">待连接的主机地址(IP地址)</param> /// <param name="portStr">待连接的端口号</param> /// <param name="connType">连接类型(UDP, TCP)</param> /// <returns>假如连接成功,返回1,否则返回0</returns> public int Connect(string serverIp, string portStr, ConnTypes connType) { string _class = MethodBase.GetCurrentMethod().ReflectedType.FullName; //命名空间+类名 string _method = string.Format("Int32 {0}", new StackTrace().GetFrame(0).GetMethod().Name); //方法名称 string connTypeName = Enum.GetName(typeof(ConnTypes), (int)connType); //连接类型的名称 //假如已连接,返回错误信息 if (IsConnected) { LastErrorCode = "001"; LastErrorMessage = string.Format("已与主机 {0} 在端口 {1} 建立{2}连接,无法再次连接!", ServerIp, ServerPort.ToString(), connTypeName); FileClient.WriteFailureInfo(new string[] { LastErrorMessage, string.Format("类名称:{0},方法名称:{1}", _class, _method) }); return(0); } //假如两个参数中有一个参数为空,则生成错误信息并抛出异常 string param = string.Empty; //参数名称 if (string.IsNullOrWhiteSpace(serverIp)) { param = "string serverIp"; LastErrorCode = "002"; LastErrorMessage = string.Format("建立{0}连接的主机地址不得为空!", connTypeName); } else if (string.IsNullOrWhiteSpace(portStr)) { param = "string portStr"; LastErrorCode = "003"; LastErrorMessage = string.Format("建立{0}连接的端口不得为空!", connTypeName); } if (!string.IsNullOrWhiteSpace(LastErrorCode)) { FileClient.WriteFailureInfo(new string[] { LastErrorMessage, string.Format("类名称:{0},方法名称:{1}", _class, _method) }); throw new ArgumentException(LastErrorMessage, param); //假如不需要抛出异常,注释此行 //return 0; } serverIp = serverIp.Equals("localhost", StringComparison.OrdinalIgnoreCase) ? "127.0.0.1" : serverIp; //判断localhost int port = int.Parse(portStr); //端口转换为数值类型 int result = 1; //判断连接类型并进行相应的连接,保存主机地址、端口与连接状态;假如报错,获取错误信息 if (connType == ConnTypes.TCP) { try { this.TcpClient = new DerivedTcpClient(serverIp, port); this.ServerIp = this.TcpClient.ServerIp; this.ServerPort = this.TcpClient.ServerPort; this.IsConnected = this.TcpClient.IsConnected; } catch (Exception) { this.LastErrorMessage = this.TcpClient.LastErrorMessage; throw; } } //TODO 编写其它连接方式的连接方法 else { //try //{ // result = BaseUdpClient.Connect(serverIp, port); // ServerIp = BaseUdpClient.ServerIp; // ServerPort = BaseUdpClient.ServerPort; // IsConnected = BaseUdpClient.IsConnected; //} //catch (Exception) { LastErrorMessage = BaseUdpClient.LastErrorMessage; throw; } } ConnType = connType; return(result); }