网络在线游戏开发心得(服务器端)(二)

类别:Java 点击:0 评论:0 推荐:

bromon原创 请尊重版权

二、通信协议

      

  这个项目并没有复杂的通信指令,命令数量很有限,但是还是有个关键问题需要关注:流量。为了尽量减小流量,我们使用字节代替字符串来保存系统指令,这样可以使流量减少一半,比如使用一个字节来保存一张扑克牌,字节高位表示花色,字节低位表示数字,如果0代表黑桃,那么黑桃三就应该是0x03,这个需要靠位操作来实现:

 

       int m=0;

       int n=3;

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

 

  游戏中需要传递用户的积分,这是一个大整数,使用四个字节来保存比较保险,将整数转换为四个字节的操作如下:

 

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;

}

 

  将四个字节转回来的操作如下:

 

       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;

}

下一篇:关于数据库连接池

本文地址:http://com.8s8s.com/it/it11865.htm