網路線上遊戲開發心得(伺服器端)(二)

來源:互聯網
上載者:User

bromon原創 請尊重著作權

二、通訊協定

      

  這個項目並沒有複雜的通訊指令,命令數量很有限,但是還是有個關鍵問題需要關註:流量。為了盡量減小流量,我們使用位元組代替字串來儲存系統指令,這樣可以使流量減少一半,比如使用一個位元組來儲存一張撲克牌,位元組高位表示花色,位元組低位表示數字,如果0代表黑桃,那麼黑桃三就應該是0x03,這個需要靠位操作來實現:

 

       int m=0;

       int n=3;

       byte card=(byte)(m)<<4)|((byte)n;          //m左移四位,然後與n左或操作

 

  遊戲中需要傳遞使用者的積分,這是一個大整數,使用四個位元組來儲存比較保險,將整數轉換為四個位元組的操作如下:

 

package org.bromon.games.al;
public static byte[] translateLong(long mark)

    {

        byte[] b = new byte[4];

        for (int i = 0; i < 4; i++)

        {

            b[i] = (byte) (mark >>> (24 - i * 8));

        }

        return b;

}

 

  將四個位元組轉回來的操作如下:


package org.bromon.games.al;
 

       public static long translateByte(byte[] b)

    {

        int mask = 0xff;

        int temp = 0;

        int res = 0;

        for (int i = 0; i < 4; i++)

        {

            res <<= 8;

            temp = b[i] & mask;

            res |= temp;

        }

        return res;

}

下一篇:關於資料庫連接池

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.