예제 #1
0
 /// <summary>
 /// 连接
 /// </summary>
 private bool Connect()
 {
     try
     {
         client.Connect(ip);
         nStream = new NetworkStream(client.Client, true);
         sk      = new Sockets(ip, client, nStream);
         sk.nStream.BeginRead(sk.RecBuffer, 0, sk.RecBuffer.Length, new AsyncCallback(EndReader), sk);
         return(true);
     }
     catch (Exception skex)
     {
         Sockets sks = new Sockets();
         sks.ex            = skex;
         sks.ClientDispose = true;
         if (pushSockets != null)
         {
             pushSockets.Invoke(sks);//推送至UI
         }
         return(false);
     }
 }
예제 #2
0
        private void ReceiveMess(Sockets sks)
        {
            ControlInvoker.Invoke(this, new ThreadStart(delegate
            {
                if (sks.ex != null)
                {
                    if (sks.ClientDispose == true)
                    {
                        //由于未知原因引发异常.导致客户端下线.   比如网络故障.或服务器断开连接.
                        //SetClientState(string.Format("客户端下线.!异常消息:{0}\r\n", sks.ex));
                    }
                    else
                    {
                        //SetClientState(string.Format("异常消息:{0}\r\n", sks.ex));
                    }
                    //timerConnect.Enabled = true;
                }
                else if (sks.Offset == 0)
                {
                    //客户端主动下线
                    // SetClientState("客户端下线.!");
                }
                else
                {
                    byte[] buffer = new byte[sks.Offset];
                    Array.Copy(sks.RecBuffer, buffer, sks.Offset);
                    string str = Encoding.UTF8.GetString(buffer);

                    strPath = Directory.GetParent(Environment.CurrentDirectory).Parent.FullName;
                    //此方式针对vs运行的程序有效,如果为直接启动exe,需要注意图片的路径

                    switch (str.Substring(0, 1))
                    {
                    case "1":
                        strPath += @"/dnf.png";

                        break;

                    case "2":
                        strPath += @"/lol.png";
                        break;

                    case "3":
                        strPath += @"/ahead.png";

                        break;
                    }
                    updateUi?.Invoke();                  //同步更新Panel
                    if (sks.Client.Client.Available > 0) //判断消息是否发送完成,socket的数据大小限制,分多个包发送
                    {
                        Console.Write(str);
                        _mess += str;
                    }
                    else
                    {
                        _mess  = "";
                        _mess += str;
                    }
                }
            }));
        }