019-直接利用Socket/TCP開發網絡遊戲二

今天咱們繼續開始學習網絡部分的知識。今天的部分是分爲兩個部分的一個數據傳送,一個是MySQL的開頭。廢話很少說咱們開始今天的內容。數組

咱們其實知道在vs中是有粘包與分包的機制的,是爲了內部的優化機制。那麼咱們應該如何去進行數據的傳出與發送呢,咱們用到的是這個類BitConverter.GetBytes這個類將全部的字符串都轉換成四個字節,咱們在tcp客戶端建立一個類message,在其中寫下以下的動心:服務器

   public class Message
    {
        public static byte[] GetBytes(string data)
        {
            //首先獲得的是傳來的字符串轉換成字節數組
            byte[] dataBytes = Encoding.UTF8.GetBytes(data);
            //接着計算長度
            int dataLength = data.Length;
            //建立新數組
            byte[] lengthByte = BitConverter.GetBytes(dataLength);//取到字節數組的長度
            byte[] newBytes = lengthByte.Concat(dataBytes).ToArray();
            return newBytes;
        }
    }

而後在在program中寫網絡

 for (int i = 0; i < 100; i++)
            {
                clientSocket.Send(Message.GetBytes(i.ToString()));
            }

接着在tcp服務器端寫message,以下tcp

 private byte[] data = new byte[1024];
        private int startIndex = 0;//開始索引
        public byte[] Data { get { return data; } }
        public int StartIndex { get { return startIndex; } }

        //還剩餘什麼
        public int RemainSize
        {
            get { return data.Length - startIndex; }
        }

        public void AddCount(int count)
        {
            startIndex += count;
        }

        //讀數據
        public void ReadMessage()
        {
            while (true)
            {
                //若是數據長度不足4的話,會返回 
                if (startIndex <= 4) return;
                //獲得傳來數據的長度,由於toint32一次只會解析前四個字節,這樣就知道了數組中還有幾個數據
                int count = BitConverter.ToInt32(data, 0);
                if ((startIndex - 4) >= count)
                {
                    //索引減4就是真正的數據長度,就接受數據
                    string s = Encoding.UTF8.GetString(data, 4, count);
                    Console.WriteLine("解析出來的數據爲:" + s);
                    //將數據進行更新
                    Array.Copy(data, count + 4, data, 0, startIndex - 4 - count);
                    startIndex -= (count + 4);
                }
                else
                {
                    break;
                }
            }
        }

在tcp的program中寫下學習

  static Message msg = new Message();
 static void AcceptCallBack(IAsyncResult ar)
        {
            Socket serverSocket = ar.AsyncState as Socket;
            Socket clientSocket = serverSocket.EndAccept(ar);
            string msgStr = "Hello Client 您好...";
            byte[] data = Encoding.UTF8.GetBytes(msgStr);
            clientSocket.Send(data);

            clientSocket.BeginReceive(msg.Data, msg.StartIndex, msg.RemainSize, SocketFlags.None, ReceiveCallBack, clientSocket);
            serverSocket.BeginAccept(AcceptCallBack, serverSocket);
        }
        static void ReceiveCallBack(IAsyncResult ar)
        {
            Socket clientSocket = null;
            try
            {
                clientSocket = ar.AsyncState as Socket;
                int count = clientSocket.EndReceive(ar);
                if (count == 0)
                {
                    clientSocket.Close();
                    return;
                }
                msg.AddCount(count);
                msg.ReadMessage();
                clientSocket.BeginReceive(msg.Data, msg.StartIndex, msg.RemainSize, SocketFlags.None, ReceiveCallBack, clientSocket);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                if (clientSocket != null)
                {
                    clientSocket.Close();
                }
            }
        }

這樣就寫了。優化

接下來是數據部分MySQL的使用就不說了,spa

//建立鏈接
            string connStr = "database=text002;data source=localhost;port=3306;user Id=root;password=root;";
            MySqlConnection conn = new MySqlConnection(connStr);
            conn.Open();

            #region 查詢
            //MySqlCommand cmd = new MySqlCommand("select *from user", conn);
            //MySqlDataReader reader = cmd.ExecuteReader();
            //while (reader.Read())
            //{
            //    string username = reader.GetString("username");
            //    string password = reader.GetString("password");
            //    Console.WriteLine(username + ":" + password);
            //}
            //reader.Close();
            #endregion

            #region 插入
            //string username = "你好"; string password = "世界";
            //MySqlCommand cmd = new MySqlCommand("insert into user set username=@un,password=@pwd", conn);
            //cmd.Parameters.AddWithValue("un", username);
            //cmd.Parameters.AddWithValue("pwd", password);         
            //cmd.ExecuteNonQuery();
            #endregion


            conn.Close();//斷開鏈接
            Console.ReadKey();

就是這麼多了。code

相關文章
相關標籤/搜索