Example #1
0
        public bool Connection(string username)
        {
            bool test = false;//Variable for test the connection

            try
            {
                Communication com = new Communication();//intantiate the objet communication.
                Tcpclient.Connect(IPAddress.Parse("10.4.0.20"), 7777);
                //Connect to the ip address give with the port 7777.
                byte[]        buffer   = new byte[1000];      //Create a table where we store what we send.
                ASCIIEncoding encoding = new ASCIIEncoding(); //Instantiates the object that allows to encode my data in byte.

                com.RequestType = CONNEXION_RESPONSE;
                com.NamePlayer  = username;

                string msg = JsonConvert.SerializeObject(com);         //Create a string message and serialise com to json
                buffer = encoding.GetBytes(msg);                       // I transform my stfing into byte to send it in TCP.
                Tcpclient.GetStream().Write(buffer, 0, buffer.Length); //I get the connection flow between the client and the server
                                                                       // .whrite allows to write on the flow of data my byte tables.

                t = new Thread(Read);                                  //Instantiate a Thread to keep the connection(function READ).
                t.Start();                                             //Start the Thread.
                test = true;                                           //The connection is established.
            }
            catch (Exception e)
            {
                //exception
            }
            return(test);//Send the variable for the test of connection.
        }
Example #2
0
 public void SendMessageToClient(string message)
 {
     try {
         NetworkStream stream   = Tcpclient.GetStream();
         byte[]        sendbyte = Encoding.ASCII.GetBytes(message);
         stream.Write(sendbyte, 0, sendbyte.Length);
     } catch (Exception e) {
         Console.WriteLine("TcpClient n'est pas défini");
     }
 }
Example #3
0
 /// <summary>
 /// 断开连接
 /// </summary>
 public void StopConnection()
 {
     //关闭连接
     Tcpclient.Close();
     //关闭线程
     Tcpthread.Abort();
     //Tcpthread = null;
     Isclosed            = false;
     IsStartTcpthreading = false;
     DelegateHelper.TcpClientStateInfo("断开连接");
     //标示线程已关闭可以重新连接
 }
Example #4
0
 public void SendData(Communication com)
 {
     try
     {
         ASCIIEncoding encoding = new ASCIIEncoding();
         com.PlayerId = game.LocalPlayerId;
         string msg    = JsonConvert.SerializeObject(com);      //Create a string message and serialise com to json
         byte[] buffer = new byte[1000];
         buffer = encoding.GetBytes(msg);                       // I transform my stfing into byte to send it in TCP.
         Tcpclient.GetStream().Write(buffer, 0, buffer.Length); // I get the connection flow between the client and the server
     }
     catch
     {
     }
 }
Example #5
0
 public void SendTestMessage(string msg)
 {
     try
     {
         ASCIIEncoding encoding = new ASCIIEncoding();
         Communication com      = new Communication();              //intantiate the objet communication.
         string        message  = JsonConvert.SerializeObject(msg); //Create a string message and serialise com to json
         byte[]        buffer   = new byte[1000];                   //Create a table where we store what we send.
         buffer = encoding.GetBytes(message);                       // I transform my stfing into byte to send it in TCP.
         Tcpclient.GetStream().Write(buffer, 0, buffer.Length);     //I get the connection flow between the client and the server
     }
     catch
     {
     }
 }
Example #6
0
 public void Read()
 {
     try
     {
         while (true)                                           //Create an infinite loop to keep the connection.
         {
             byte[]        bytes             = new byte[10000]; //Create a table where we store what we receve.
             StringBuilder MyCompleteMessage = new StringBuilder();
             do
             {
                 int NbrOfBytesRead = Tcpclient.GetStream().Read(bytes, 0, bytes.Length);
                 MyCompleteMessage.AppendFormat("{0}", Encoding.UTF8.GetString(bytes, 0, NbrOfBytesRead));
             }while (Tcpclient.GetStream().DataAvailable);
             Communication com = JsonConvert.DeserializeObject <Communication>(MyCompleteMessage.ToString());
             RedirectReceiveData(com);
         }
     }
     catch
     {
     }
 }
Example #7
0
        /// <summary>
        /// 断开连接
        /// </summary>
        public void StopConnection()
        {
            IsStart             = false;
            IsReconnection      = false;
            IsStartTcpthreading = false;

            Thread.Sleep(10);
            if (Tcpclient != null)
            {
                //关闭连接
                Tcpclient.Close();
            }
            if (Tcpthread != null)
            {
                Tcpthread.Interrupt();
                //关闭线程
                Tcpthread.Abort();
                //Tcpthread = null;
            }

            OnTcpClientStateInfoEnterHead("断开连接", SocketState.Disconnect);
            //标示线程已关闭可以重新连接
        }
Example #8
0
        /// <summary>
        ///  线程接收Socket上传的数据
        /// </summary>
        private void StartTcpThread()
        {
            byte[] receivebyte = new byte[1024];
            int    bytelen;

            try
            {
                while (IsStartTcpthreading)
                {
                    if (!Tcpclient.Connected)
                    {
                        try
                        {
                            if (ReConectedCount != 0)
                            {
                                //返回状态信息
                                DelegateHelper.TcpClientStateInfo(string.Format("正在第{0}次重新连接服务器... ...", ReConectedCount));
                            }
                            else
                            {
                                //SocketStateInfo
                                DelegateHelper.TcpClientStateInfo("正在连接服务器... ...");
                            }
                            Tcpclient.Connect(IPAddress.Parse(ServerIp), ServerPort);
                            DelegateHelper.TcpClientStateInfo("已连接服务器");
                            //Tcpclient.Client.Send(Encoding.Default.GetBytes("login"));
                        }
                        catch
                        {
                            //连接失败
                            ReConectedCount++;
                            //强制重新连接
                            Isclosed            = false;
                            IsStartTcpthreading = false;
                            //每三秒重连一次
                            Thread.Sleep(ReConnectionTime);
                            continue;
                        }
                    }
                    bytelen = Tcpclient.Client.Receive(receivebyte);
                    // 连接断开
                    if (bytelen == 0)
                    {
                        //返回状态信息
                        DelegateHelper.TcpClientStateInfo("与服务器断开连接... ...");
                        // 异常退出、强制重新连接
                        Isclosed            = false;
                        ReConectedCount     = 1;
                        IsStartTcpthreading = false;
                        continue;
                    }
                    Receivestr = ASCIIEncoding.Default.GetString(receivebyte, 0, bytelen);
                    if (Receivestr.Trim() != "")
                    {
                        //接收数据
                        DelegateHelper.TcpClientReceive(Receivestr);
                    }
                }
                //此时线程将结束,人为结束,自动判断是否重连
                CreateTcpClient();
            }
            catch (Exception ex)
            {
                //CreateTcpClient();
                //返回错误信息
                DelegateHelper.TcpClientErrorMsg("错误信息:" + ex.Message);
            }
        }
Example #9
0
        /// <summary>
        ///  线程接收Socket上传的数据
        /// </summary>
        private void StartTcpThread()
        {
            byte[] receivebyte = new byte[2048];
            int    bytelen;

            try
            {
                while (IsStartTcpthreading)
                {
                    #region

                    if (!Tcpclient.Connected)
                    {
                        try
                        {
                            if (ReConectedCount != 0)
                            {
                                //返回状态信息
                                OnTcpClientStateInfoEnterHead(
                                    string.Format("正在第{0}次重新连接服务器... ...", ReConectedCount),
                                    SocketState.Reconnection);
                            }
                            else
                            {
                                //SocketStateInfo
                                OnTcpClientStateInfoEnterHead("正在连接服务器... ...", SocketState.Connecting);
                            }
                            Tcpclient.Connect(IPAddress.Parse(ServerIp), ServerPort);
                            OnTcpClientStateInfoEnterHead("已连接服务器", SocketState.Connected);
                            //Tcpclient.Client.Send(Encoding.Default.GetBytes("login"));
                        }
                        catch
                        {
                            //连接失败
                            ReConectedCount++;
                            //强制重新连接
                            IsReconnection      = true;
                            IsStartTcpthreading = false;
                            //每三秒重连一次
                            Thread.Sleep(ReConnectionTime);
                            continue;
                        }
                    }
                    //Tcpclient.Client.Send(Encoding.Default.GetBytes("login"));
                    bytelen = Tcpclient.Client.Receive(receivebyte);
                    // 连接断开
                    if (bytelen == 0)
                    {
                        //返回状态信息
                        OnTcpClientStateInfoEnterHead("与服务器断开连接... ...", SocketState.Disconnect);
                        // 异常退出、强制重新连接
                        IsReconnection      = true;
                        ReConectedCount     = 1;
                        IsStartTcpthreading = false;
                        continue;
                    }
                    Receivestr = ASCIIEncoding.Default.GetString(receivebyte, 0, bytelen);
                    byte[] bytes = new byte[bytelen];
                    Array.Copy(receivebyte, 0, bytes, 0, bytelen);
                    //OnTcpClientRecevice(bytes);
                    if (Receivestr.Trim() != "")
                    {
                        //接收数据
                        try
                        {
                            OnTcpClientRecevice(Receivestr, bytes);
                        }
                        catch (Exception ex)
                        {
                            //返回错误信息
                            OnTcpClientErrorMsgEnterHead("错误信息:" + ex.Message);
                        }
                    }
                    #endregion
                }
                //此时线程将结束,人为结束,自动判断是否重连
                IsReconnection = true;
                CreateTcpClient();
            }
            catch (Exception ex)
            {
                IsReconnection = true;
                CreateTcpClient();
                //返回错误信息
                try
                {
                    OnTcpClientErrorMsgEnterHead("错误信息:" + ex.Message);
                }
                catch { }
            }
        }