Ejemplo n.º 1
0
        /// <summary>
        /// 从Tcp服务端获取信息的回调函数
        /// </summary>
        /// <param name="ar"></param>
        private void TcpCallBack(IAsyncResult ar)
        {
            DerivedTcpClient client = (DerivedTcpClient)ar.AsyncState;
            NetworkStream    ns     = client.NetStream;

            try
            {
                byte[] recdata = new byte[ns.EndRead(ar)];

                Array.Copy(client.Buffer, recdata, recdata.Length);
                //receivedEventArgs.ReceivedData = recdata;
                //receivedEventArgs.ReceivedInfo = HexHelper.ByteArray2HexString
                if (recdata.Length > 0)
                {
                    if (DataReceived != null)
                    {
                        DataReceived.BeginInvoke(client.Name, new Events.DataReceivedEventArgs(recdata), null, null); //异步输出数据
                    }
                    raiser.Click();
                    if (ReceiveRestTime > 0)
                    {
                        Thread.Sleep(ReceiveRestTime);
                    }
                    if (AutoReceive)
                    {
                        ns.BeginRead(client.Buffer, 0, client.Buffer.Length, new AsyncCallback(TcpCallBack), client);
                    }
                }
            }
            catch (Exception ex)
            {
                FileClient.WriteExceptionInfo(ex, string.Format("从TcpServer获取数据的过程中出错:IP地址{0},端口{1}", ServerIp, ServerPort), true);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 从Tcp服务端获取信息的回调函数
        /// </summary>
        /// <param name="ar"></param>
        private void SocketCallBack(IAsyncResult ar)
        {
            DerivedTcpClient client = (DerivedTcpClient)ar.AsyncState;
            NetworkStream    ns     = client.NetStream;

            try
            {
                byte[] recdata = new byte[ns.EndRead(ar)];
                Array.Copy(client.Buffer, recdata, recdata.Length);
                //this.receivedEventArgs.ReceivedData = recdata;
                //this.receivedEventArgs.ReceivedInfo = HexHelper.ByteArray2HexString
                if (recdata.Length > 0)
                {
                    if (this.DataReceived != null)
                    {
                        this.DataReceived.BeginInvoke(client.Name, new CommonLib.Events.DataReceivedEventArgs(recdata), null, null); //异步输出数据
                    }
                    ns.BeginRead(client.Buffer, 0, client.Buffer.Length, new AsyncCallback(SocketCallBack), client);
                }
            }
            catch (Exception ex)
            {
                FileClient.WriteExceptionInfo(ex, string.Format("从TcpServer获取数据的过程中出错:IP地址{0},端口{1}", this.ServerIp, this.ServerPort), true);
            }
        }
Ejemplo n.º 3
0
        /// <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);
        }