private void Start() { if (tcpClient == null) { tcpClient = new TCPClient(); tcpClient.PacketReceived +=new TCP_Client.PacketReceivedEventHandler(tcpClient_PacketReceived); tcpClient.Connected += new EventHandler(tcpClient_Connected); tcpClient.Disonnected += new EventHandler(tcpClient_Disonnected); } tcpClient.Connect(ServerEP.Address.ToString(), ServerEP.Port); System.Timers.Timer timer = new System.Timers.Timer(); if (timer == null) { int count = 0; timer = new System.Timers.Timer(); timer.Interval = 3000; timer.Enabled = true; timer.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e) { if (IsConnected)//如果连接到服务器 { timer.Enabled = false; timer = null; } else if (count < 3)//如果9秒以后还未连接到服务器 { tcpClient.Connect(ServerEP.Address.ToString(), ServerEP.Port); Console.WriteLine("try connecte!"+ count.ToString()); } else if (count >= 3)//如果3秒后还未连接,则退出连接操作 { Console.WriteLine("connecte filad!" ); timer.Enabled = false; timer = null; } count++; }; } }
/// <summary> /// 设置登录用户在线状态 /// </summary> /// <param name="showType"></param> public void setMyPresence(IMLibrary3.Enmu.ShowType showType) { if (showType == MyAuth.ShowType)//如果状态未做改变,则无需发送到服务器 return; if (showType == IMLibrary3.Enmu.ShowType.Offline && (tcpClient != null && !tcpClient.IsDisposed && tcpClient.IsConnected)) //如果要下线 { this.tcpClient.Disconnect(); this.tcpClient.Dispose(); this.tcpClient = null; return; } if (showType != IMLibrary3.Enmu.ShowType.Offline && (tcpClient == null || tcpClient.IsDisposed || !tcpClient.IsConnected))//如果已经下线,则上线 { MyAuth.ShowType = showType; Login(MyAuth, true);//登录。。。 return; } Presence pre = new Presence(); pre.from = MyAuth.UserID; pre.ShowType = showType; pre.type = type.set;//必须设置 set,以表示是设置,如果为get,则是获取所有联系人的状态 SendMessageToServer(pre ); }
/// <summary> /// 开始登录 /// </summary> /// <param name="auth">登录用户参数</param> /// <param name="IsOutTime">是否超时时钟重复的登录</param> public void Login(IMLibrary3.Protocol.Auth auth, bool IsOutTime) { if (myPassword!="")//如果已经登录成功过 auth.Password = myPassword;//将正确的密码设置为登录密码 MyAuth = auth;//暂存自己的登录信息于内存 if (tcpClient == null || tcpClient.IsDisposed) { tcpClient = new TCPClient(); tcpClient.PacketReceived += new TCP_Client.PacketReceivedEventHandler(tcpClient_PacketReceived); tcpClient.Disonnected += new EventHandler(tcpClient_Disonnected); } if (!tcpClient.IsConnected) tcpClient.Connect(Global.ServerDomain,Global.ServerMsgPort); if (!this.timerLogin1.Enabled) this.timerLogin1.Enabled = true; SendMessageToServer(auth);//向服务器登录 }