关于C# 对接Http 协议和Socket 协议

来源:互联网 发布:淘宝店铺客服招聘 编辑:程序博客网 时间:2024/05/16 18:38

首先我们先写一个类,这个类是消息抽象类 packet

using System;using System.Collections.Generic;using System.Linq;using System.Text;using UnityEngine;using System.Collections;    //消息抽象类    public abstract class Packet:MonoBehaviour    {        protected int opcode = -1;// 消息号        public Packet(int opcode)        {            this.opcode = opcode;        }        public void setOpcode(int opcode)        {            this.opcode = opcode;        }        public int getOpcode()        {            return this.opcode;        }        public abstract void destroy();    }

接下来我写一个写消息的类,继承上面的消息抽象类。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using UnityEngine;using System.Collections;public class LinkWriteOnlyPacket:Packet{    protected int wirteLegnth = 0;// 消息体长度    protected byte[] writeData = null;    protected byte[] writeData1 = null;    protected byte[] buf = new byte[64];    private int writeCount = 0;// 当前写入的二进制长度    protected bool isFlushed = false;// 写入的二进制是否刷新    protected bool sendImmediately = true;// 是否及时写出    /**消息内容前占用的字符*/    private  const byte ISLONGTH=4;    public LinkWriteOnlyPacket(int code)        : base(code)    {        if (code % 2 != 0&&code!=0) {         Debug.Log("发送消息=" + code );        }        //本次发送的消息号        this.writeShort(code);        //玩家本次登录的身份秘钥        this.writeUTF(Player.Pwdkey);    }    public int getWriteLength()    {        return getWriteData().Length;    }    public byte[] getWriteData()    {        if (!isFlushed)        {            try            {                this.flush();            }            catch (Exception e)            {            }        }        return this.writeData;    }    public  void flush()   {        this.writeData = null;        this.writeData = new byte[writeCount];        //System.arraycopy(buf, 0, this.writeData, 0, writeCount);      //  buf.CopyTo(this.writeData,0);        Array.Copy(buf, this.writeData, writeCount);        isFlushed = true;    }    public  void writeByte(int b)   {        int newcount = writeCount + 1;        if (newcount > buf.Length) {            //buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));            byte[] by = new byte[buf.Length+1];            buf.CopyTo(by, 0);            buf = by;        }        buf[writeCount] = (byte) b;        writeCount = newcount;    }    public void writeBoolean(bool b)    {        writeByte(b ? 1 : 0);    }    public  void writeShort(int v)   {        int newcount = writeCount + 2;        if (newcount > buf.Length) {             byte[] by = new byte[buf.Length+2];            buf.CopyTo(by, 0);            buf = by;        }        buf[writeCount] = (byte) (rightMove(v,8) & 0xFF);        buf[writeCount + 1] = (byte)(rightMove(v, 0) & 0xFF);        writeCount = newcount;    }    public  void writeInt(int v)   {        int newcount = writeCount + 4;        if (newcount > buf.Length) {            //buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));            byte[] by = new byte[buf.Length+4];            buf.CopyTo(by, 0);            buf = by;        }        buf[writeCount] = (byte) (rightMove(v,24) & 0xFF);        buf[writeCount + 1] = (byte) (rightMove(v,16) & 0xFF);        buf[writeCount + 2] = (byte) (rightMove(v,8) & 0xFF);        buf[writeCount + 3] = (byte)(rightMove(v, 0) & 0xFF);        writeCount = newcount;    }    public  void writeLong(long v)   {        int newcount = writeCount + 8;        if (newcount > buf.Length) {            //buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));              byte[] by = new byte[buf.Length+8];            buf.CopyTo(by, 0);            buf = by;        }        buf[writeCount] = (byte) (rightMoves(v,56));        buf[writeCount + 1] = (byte) (rightMoves(v,48));        buf[writeCount + 2] = (byte) (rightMoves(v,40));        buf[writeCount + 3] = (byte) (rightMoves(v,32));        buf[writeCount + 4] = (byte) (rightMoves(v,24));        buf[writeCount + 5] = (byte) (rightMoves(v,16));        buf[writeCount + 6] = (byte) (rightMoves(v,8));        buf[writeCount + 7] = (byte)(rightMoves(v, 0));        writeCount = newcount;    }    public  void writeFloat(float v)   {        //writeInt(Float.floatToIntBits(v));        //writeInt(Convert.ToInt32(v));        writeInt(BitConverter.ToInt32(BitConverter.GetBytes(v), 0));        //int s = BitConverter.ToInt32(BitConverter.GetBytes(v), 0);    }    public  void writeDouble(double v)   {        //writeLong(Double.doubleToLongBits(v));        writeLong(BitConverter.ToInt64(BitConverter.GetBytes(v), 0));        //long s = BitConverter.ToInt64(BitConverter.GetBytes(v), 0);    }    //public void writeUTF(string num)    //{    //    byte[] GetByteString = new byte[] { };    //    GetByteString = System.Text.Encoding.UTF8.GetBytes(num);    //    // GetByteString = System.Text.Encoding.ASCII.GetBytes(num);//ASCII    //    //GetByteString = System.Text.Encoding.Unicode.GetBytes(num);//Unicode    //    writeBytes(GetByteString);    //}    int  i= 0;   public void writeUTF(String str) {        /**         * 防止空指针造成异常,出现空指针的时候,写一个空串         */        if (str == null) {            str = "";        }        int strlen = str.Length;        int utflen = 0;        int c, num = 0;        for (int j = 0; j < strlen; j++) {            c = char.Parse(str.Substring(j,1));            if ((c >= 0x0001) && (c <= 0x007F)) {                utflen++;            } else if (c > 0x07FF) {                utflen += 3;            } else {                utflen += 2;            }        }        if (utflen > 65535)            return;        byte[] bytearr = new byte[utflen + 2];        bytearr[num++] = (byte) (rightMove(utflen,8) & 0xFF);        bytearr[num++] = (byte) (rightMove(utflen,0) & 0xFF);        for (i = 0; i < strlen; i++) {           c = char.Parse(str.Substring(i,1));            if (!((c >= 0x0001) && (c <= 0x007F)))                break;            bytearr[num++] = (byte) c;        }        for (; i < strlen; i++) {            c = char.Parse(str.Substring(i, 1));            if ((c >= 0x0001) && (c <= 0x007F)) {                bytearr[num++] = (byte) c;            } else if (c > 0x07FF) {                bytearr[num++] = (byte) (0xE0 | ((c >> 12) & 0x0F));                bytearr[num++] = (byte) (0x80 | ((c >> 6) & 0x3F));                bytearr[num++] = (byte) (0x80 | ((c >> 0) & 0x3F));            } else {                bytearr[num++] = (byte) (0xC0 | ((c >> 6) & 0x1F));                bytearr[num++] = (byte) (0x80 | ((c >> 0) & 0x3F));            }        }        //return bytearr;        writeBytes(bytearr);    } public  void writeBytes(byte[] bytes)  {        int newcount = writeCount + bytes.Length;        if (newcount > buf.Length)        {            //buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));            byte[] by = new byte[newcount];            buf.CopyTo(by, 0);            buf = by;        }        //System.arraycopy(bytes, 0, buf, writeCount, bytes.length);        Array.Copy(bytes, 0, buf, writeCount, bytes.Length);        writeCount = newcount;    }    public override void destroy() {        this.writeData = null;        this.buf = null;        this.writeData1=null;    }    public static long rightMoves(long value, int pos)    {        if (pos != 0)  //移动 0 位时直接返回原值        {            long mask = 0x7fffffffffffffff; ;     // int.MaxValue = 0x7FFFFFFF 整数最大值            value >>= 1;     //第一次做右移,把符号也算上,无符号整数最高位不表示正负            //                                          但操作数还是有符号的,有符号数右移1位,正数时高位补0,负数时高位补1            value &= mask;     //和整数最大值进行逻辑与运算,运算后的结果为忽略表示正负值的最高位            value >>= pos - 1;     //逻辑运算后的值无符号,对无符号的值直接做右移运算,计算剩下的位        }        return value;    }    public static int rightMove(int value, int pos)    {        if (pos != 0)  //移动 0 位时直接返回原值        {            int mask = 0x7fffffff;     // int.MaxValue = 0x7FFFFFFF 整数最大值            value >>= 1;     //第一次做右移,把符号也算上,无符号整数最高位不表示正负            //                                          但操作数还是有符号的,有符号数右移1位,正数时高位补0,负数时高位补1            value &= mask;     //和整数最大值进行逻辑与运算,运算后的结果为忽略表示正负值的最高位            value >>= pos - 1;     //逻辑运算后的值无符号,对无符号的值直接做右移运算,计算剩下的位        }        return value;    }    //public void writeBytes(byte[] bytes)    //{    //    int newcount = writeCount + bytes.Length;    //    if (newcount > buf.Length)    //    {    //        //buf = Arrays.copyOf(buf, Math.Max(buf.Length << 1, newcount));    //        byte[] by = new byte[newcount];    //        buf.CopyTo(by, 0);    //        buf = by;    //    }    //    //System.arraycopy(bytes, 0, buf, writeCount, bytes.Length);    //    Array.Copy(bytes, 0, buf, writeCount, bytes.Length);    //    writeCount = newcount;    //}    /**发送http消息*/    public static void writePacket(string url,byte[] message)    {        try        {            HttpMessage hs = new HttpMessage();          //  hs.Ceshi(url,message);            HttpMessage.sendHttp(url,message);        }        catch (Exception e)        {        }    }    /**发送Socket消息*/    public static void writeSocketPacket( byte[] message)    {        try        {            SocketMessage.sendNewToServer(message);            Debug.Log("writeSocketPacket=over");        }        catch (Exception e)        {        }    }}

然后是一个读取消息的类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public abstract class LinkReadAndWritePacket : LinkWriteOnlyPacket
{
protected byte[] readData = null;//读的二进制数据
private int readPosition = 0; //当前读取的位置
protected bool writeLog = false;

protected bool requestCrypt = false;public LinkReadAndWritePacket(int code, byte[] readData)    : base(code){    this.readData = readData;}public int remaining(){    return readData.Length - readPosition;}public int readBytes(byte[] bytes){    if (readPosition + bytes.Length > readData.Length)    {        //  new BufferOverflowException().printStackTrace();        return 0;    }    for (int i = 0; i < bytes.Length; i++)    {        bytes[i] = readData[readPosition++];    }    return bytes.Length;}public sbyte readByte(){    return (sbyte)this.readData[readPosition++];}public float readFloat(){    return BitConverter.ToSingle(BitConverter.GetBytes(readInt()), 0);    //  return Float.intBitsToFloat(readInt()); writeInt(BitConverter.ToInt32(BitConverter.GetBytes(v), 0));    //return readInt(BitConverter.ToDouble(readInt(), 0));}public bool readBoolean(){    return this.readData[readPosition++] == 1 ? true : false;}public short readShort(){    return (short)(((readData[readPosition++] << 8) | readData[readPosition++] & 0xff));}public int readInt(){    int offset = readPosition;    readPosition += 4;    return readData[offset + 3] & 0xff | (readData[offset + 2] & 0xff) << 8     | (readData[offset + 1] & 0xff) << 16 | (readData[offset] & 0xff) << 24;}public long readLong(){    int offset = readPosition;    readPosition += 8;    return (((long)readData[offset] << 56) +            ((long)(readData[offset + 1] & 255) << 48) +    ((long)(readData[offset + 2] & 255) << 40) +            ((long)(readData[offset + 3] & 255) << 32) +            ((long)(readData[offset + 4] & 255) << 24) +            ((readData[offset + 5] & 255) << 16) +            ((readData[offset + 6] & 255) << 8) +            ((readData[offset + 7] & 255) << 0));}public double readDouble(){    //  return Double.longBitsToDouble(readLong());    return BitConverter.ToDouble(BitConverter.GetBytes(readLong()), 0);}public int readUnsignedShort(){    return (((readData[readPosition++] & 0xff) << 8) | (readData[readPosition++] & 0xff));}public short readUnsignedByte(){    return (short)(readData[readPosition++] & 0xff);}public long readUnsignedInt(){    return ((long)(readData[readPosition++] << 24 | readData[readPosition++] << 16            | readData[readPosition++] << 8 | readData[readPosition++])) & 0xFFFFFFFFL;}public String readUTF(){    int utflen = readUnsignedShort();    byte[] bytearr = new byte[utflen];    char[] chararr = new char[utflen];    int c = 0, char2 = 0, char3 = 0;    int count = 0;    int chararr_count = 0;    // System.arraycopy(readData, readPosition, bytearr, 0, utflen);    Array.Copy(readData, readPosition, bytearr, 0, utflen);    while (count < utflen)    {        c = (int)bytearr[count] & 0xff;        if (c > 127) break;        count++;        chararr[chararr_count++] = (char)c;    }    while (count < utflen)    {        c = (int)bytearr[count] & 0xff;        switch (c >> 4)        {            case 0:            case 1:            case 2:            case 3:            case 4:            case 5:            case 6:            case 7:                count++;                chararr[chararr_count++] = (char)c;                break;            case 12:            case 13:                count += 2;                if (count > utflen)                    return null;                //  throw new UTFDataFormatException(                //     "malformed input: partial character at end");                char2 = (int)bytearr[count - 1];                if ((char2 & 0xC0) != 0x80)                    return null;                //      throw new UTFDataFormatException(                //        "malformed input around byte " + count);                 chararr[chararr_count++] = (char)(((c & 0x1F) << 6) |                                                (char2 & 0x3F));                break;            case 14:                count += 3;                if (count > utflen)                    return null;                //    throw new UTFDataFormatException(                //        "malformed input: partial character at end");                char2 = (int)bytearr[count - 2];                char3 = (int)bytearr[count - 1];                if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))                    return null;                //  throw new UTFDataFormatException(                //       "malformed input around byte " + (count-1));                chararr[chararr_count++] = (char)(((c & 0x0F) << 12) |                                                ((char2 & 0x3F) << 6) |                                                ((char3 & 0x3F) << 0));                break;            default:                return null;            //    throw new UTFDataFormatException(            //      "malformed input around byte " + count);        }    }    readPosition += utflen;    return new String(chararr, 0, chararr_count);}public void setReadData(byte[] data){    this.readData = data;}public int getReadLength(){    return readData == null ? 0 : readData.Length;}public override void destroy(){    //   super.destroy();    this.readData = null;    //  this.channel = null;}public bool isWriteLog(){    return this.writeLog;}public bool isRequestCrypt(){    return requestCrypt;}public String getActionDetail(){    return "";}//  public abstract void process();public long readUnInt(){    int offset = readPosition;    readPosition += 4;    return (((long)(readData[offset] & 255) << 24) +            ((readData[offset + 1] & 255) << 16) +            ((readData[offset + 2] & 255) << 8) +            ((readData[offset + 3] & 255) << 0));}//此方法返回读取后剩余的数据public byte[] getByteData(){    this.writeData = null;    this.writeData = new byte[readData.Length - readPosition];    //System.arraycopy(buf, 0, this.writeData, 0, writeCount);    //  buf.CopyTo(this.writeData,0);    Array.Copy(readData, readPosition, this.writeData, 0, readData.Length - readPosition);    return writeData;}public abstract void process();/** *所有socket的子协议必须重写此方法 */public virtual void socketProcess(){}

}

然后写一个LinkBaseReadPacket类

using System;using System.Collections.Generic;using System.Linq;using System.Text;    class LinkBaseReadPacket:LinkReadAndWritePacket    {        public LinkBaseReadPacket(byte[] message):base(0,message)         {        }        public override void process()        { }    }

然后是一个消息解析类

using System;using System.Collections.Generic;using System.Linq;using System.Text;using UnityEngine;/**  消息解析类 * 2016.6.24 */public class PacketFactory{    public static LinkReadAndWritePacket getPacket(int code, byte[] readData)    {        GameLoginWnd.Instance.code = code;        CreateRoleWnd.Instance.code = code;        Debug.Log("接收消息=" + code);        switch (code)        {            //测试协议            case 112:                return new TestStoC(code, readData);            case 2:                return new RegisterSTOC(code, readData);            case 4:                return new LoginSTOC(code, readData);            case 102:                return new LoginsSTOC(code, readData);            case 104:                return new CreateRoleSTOC(code, readData);            case 108:                return new NameSetSTOC(code, readData);            case 110:                return new CheckNameSTOC(code, readData);            case 8:                return new GeneralErrorSTOC(code, readData);            case 106:                return new EnterGameSTOC(code, readData);            case 412:                return new ClientBattleSTOC(code, readData);            case 402:                return new GetDupDataSTOC(code, readData);            case 404:                return new OpenDuplicateSTOC(code, readData);            case 602:                return new GetRankingSTOC(code, readData);            case 302:                return new SignSTOC(code, readData);            case 502:                return new SystemNoticeSTOC(code, readData);            case 506:                return new RoleUpmoneySTOC(code, readData);            case 406:                return new RewardDuplicateSTOC(code, readData);            case 702:                return new GetLuckySTOC(code, readData);            case 704:                return new LuckySTOC(code, readData);            case 902:                return new GetEmailSTOC(code, readData);            case 904:                return new EmailSTOC(code, readData);            case 906:                return new SendEmailSTOC(code, readData);            case 908:                return new GiveFriendEnergySTOC(code, readData);            case 408:                return new ChapDupRewardSTOC(code, readData);            case 1002:                return new LoadFriendListSTOC(code, readData);            case 1004:                return new AddFriendSTOC(code, readData);            case 1006:                return new AgreedAddFriendSTOC(code, readData);            case 1008:                return new DeleteFriendSTOC(code, readData);            case 1010:                return new RefuseAddFriendSTOC(code, readData);            case 1012:                return new RecommendFriendSTOC(code, readData);            //            case 802:                return new GetDailyTaskArraySTOC(code, readData);            case 804:                return new UpdateTaskDataSTOC(code, readData);            case 1102:                return new GetShoppingSTOC(code, readData);            case 1104:                return new ShoppingSTOC(code, readData);            case 1106:                return new ReceiveMallSTOC(code, readData);            case 134:                return new HeartSTOC(code, readData);            case 202:                return new GetBagGoodsSTOC(code, readData);            case 204:                return new UseBagGoodsSTOC(code, readData);            case 1302:                return new UpLoadPrintSTOC(code, readData);            case 116:                return new GMCommandSTOC(code, readData);            case 508:                return new EnergyChangeSTOC(code, readData);            case 1508:                return new AddPorintLadderHighMatchSTOC(code, readData);            case 1510:                return new FieldVictoryLadderHighMatchSTOC(code, readData);            case 1502:                return new SignUpLadderHighSTOC(code, readData);            case 1504:                return new StartUpLadderHighMatchSTOC(code, readData);            case 1506:                return new UsePropLadderHighMatchSTOC(code, readData);            case 1512:                return new LadderHighHalfwayExceptionSTOC(code, readData);            case 1408:                return new GetHomemadeShutAddressAndIdSTOC(code, readData);            case 1406:                return new ReceiveRewardSTOC(code, readData);            case 1602:                return new GetLBSPVEBattleSTOC(code, readData);            case 1604:                return new LBSPVEReceiveRewardSTOC(code, readData);        }        return null;    }}

然后是一个处理http协议服务器响应数据解析的类

using System;using System.Collections.Generic;using System.Linq;using System.Text;using UnityEngine;/** 此类处理http协议服务器响应数据解析 * 2016.6.24 */public class HttpHandler{    //消息头长度    private  const byte ISLONGTH=2;    public static  void messageReceived(byte[] message)    {        //消息小于最小长度        if (message.Length < ISLONGTH)        {            return;        }        LinkReadAndWritePacket readpacket = new LinkBaseReadPacket( message);        //消息包总长度        int messageCount = readpacket.readShort();        //如果消息包大于最大值就不往下执行        if (messageCount >= 65535)        {            return;        }        int pwdkey = readpacket.readShort();        //消息号        int opcode = readpacket.readShort();       Debug.Log("接收到协议=="+opcode);        //加密号        //      int pwdkey=cbuffer.getUnsignedShort(readerIndex);        LinkReadAndWritePacket packet = PacketFactory.getPacket(opcode, readpacket.getByteData());        //肯能未来会在此处设置秘钥        try        {            packet.process();            //此处执行多个消息处理的解析            while (true)            {                byte[] array = packet.getByteData();                Debug.Log("=查看多包长度=" + array.Length);                if (array == null || array.Length < ISLONGTH)                {                    return;                }                packet.destroy();                packet = null;                messageReceived(array);            }        }        catch (Exception ex)        {        }        finally        {            packet.destroy();            packet = null;        }    }}

然后是一个发送http消息到服务器

using UnityEngine;using System.Collections;using System.Collections.Generic;using System.Reflection;using System.IO;using System;using System.Threading;using System.Diagnostics;using Debug = UnityEngine.Debug;/** 此类为http协议请求响应类 * 所有http请求的发送都要调用此类的send方法 * 2016.6.24 */public class HttpMessage : MonoBehaviour{    //发送http消息到服务器    public static void sendHttp(string url, byte[] message)     {        try        {            WWW www_instance = new WWW(url, message);            Stopwatch sw = new Stopwatch();            sw.Start();            byte[] ty = new byte[0];            while (!www_instance.isDone)            {                if (sw.ElapsedMilliseconds >= 1000)                {                    if (www_instance.error != null)                    {                        Debug.Log("连接超时-----请稍后");                        MessageBoxWnd.Instance.Show("连接超时---- - 请稍后");                        sw.Stop();                        break;                    }                    else                    {                        if (sw.ElapsedMilliseconds >= 4500)                        {                            ty = www_instance.bytes;                            if (ty.Length == 0)                            {                                MessageBoxWnd.Instance.Show("连接超时---- - 请稍后,没有返回数据");                                sw.Stop();                                break;                            }                        }                    }                }            }            sw.Stop();            //yield return www_instance;            //t = www_instance.bytes;            //此类处理消息解析            //Hander(www_instance);            //   Thread.Sleep(1000);            //byte[] ty = new byte[0];            //while (ty.Length == 0)            //{            //    try            //    {            //         //  Thread.Sleep(1000);            //           if (www_instance.error != null)            //           {            //               Debug.Log("连接超时-----请稍后");            //               MessageBoxWnd.Instance.Show("连接超时---- - 请稍后");            //               break;            //           }            //           else            //           {            //               Debug.Log("hhaa");            //           //    Thread.Sleep(500);            //               ty = www_instance.bytes;            //          //     Thread.Sleep(500);            //               if (ty.Length == 0)            //               {            //                   MessageBoxWnd.Instance.Show("连接超时---- - 请稍后,没有返回数据");            //                   break;            //               }            //           }            //    }            //    catch (Exception)            //    {                               //        throw;            //    }                         //}            ty = www_instance.bytes;            HttpHandler.messageReceived(ty);            }        catch (Exception)        {           // throw;        }       // StartCoroutine(Hander(www_instance));        //LinkReadAndWritePacket readpacket = new LinkReadAndWritePacket(t);        //short one = readpacket.readShort();        //short two = readpacket.readShort();        //short three = readpacket.readShort();        ////   int fore = readpacket.readUnsignedShort();        //byte a = readpacket.readByte();        //short b = readpacket.readShort();        //int c = readpacket.readInt();        //long d = readpacket.readLong();        //float e = readpacket.readFloat();        //double f = readpacket.readDouble();        //string g = readpacket.readUTF();        //for (int i = 0; i < t.Length; i++)        //{        //    Debug.Log(t[i]);        //}    }    public void Ceshi(string url, byte[] message)    {        StartCoroutine(EE());        //    StartCoroutine(xx(url,message));        //   xx(url, message);    }    IEnumerator EE()    {        Debug.Log("dd");        yield return new WaitForSeconds(2);        Debug.Log("dd");    }    IEnumerator xx(string url, byte[] message)    {        WWW www_instance = new WWW(url, message);        yield return www_instance;        if (www_instance.isDone)        {            HttpHandler.messageReceived(www_instance.bytes);        }        if (www_instance.error != null)        {            Debug.Log(www_instance.error);        }        else        {            Debug.Log("hhaa");        }    }}

Socket 协议的两个处理类

using System;using System;using System.Collections.Generic;using System.Linq;using System.Text;using UnityEngine;/** 此类处理http协议服务器响应数据解析 * 2016.6.24 */public class SocketHandler{    //消息头长度    private const byte ISLONGTH = 2;    public static void messageReceived(byte[] message)    {        //Debug.Log("处理http协议服务器");        //消息小于最小长度        if (message.Length < ISLONGTH)        {            return;        }        LinkReadAndWritePacket readpacket = new LinkBaseReadPacket(message);        //消息包总长度        int messageCount = readpacket.readShort();        //如果消息包大于最大值就不往下执行        if (messageCount >= 65535)        {            return;        }        int pwdkey = readpacket.readShort();        //消息号        int opcode = readpacket.readShort();        Debug.Log("Socket接收到协议==" + opcode);        //加密号        //      int pwdkey=cbuffer.getUnsignedShort(readerIndex);        LinkReadAndWritePacket packet = PacketFactory.getPacket(opcode, readpacket.getByteData());        //肯能未来会在此处设置秘钥        try        {            packet.process();        }        catch (Exception ex)        {        }        finally        {            packet.destroy();            packet = null;        }    }}

第二个类

using UnityEngine;using System.Collections;using System.Collections.Generic;using System.Reflection;using System.IO;using System;using System.Threading;using System.Diagnostics;using Debug = UnityEngine.Debug;using System.Net.Sockets;using System.Net;/** 此类为Socket协议请求响应类 * 所有Socket请求的发送都要调用此类的sendNewToServer方法 * 2016.8.17 */public class SocketMessage{    //和服务器通讯的socket通道对象    private static Socket clientSocket = null;    //接收服务器推送过来的消息    static Thread readThread;    private static byte[] result = new byte[50000];    //如果socket为空生成一个socket对象且和服务器做好链接    private static void loadSocketStart()    {        IPAddress ip = IPAddress.Parse(Player.SocketIP);        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);        try        {            clientSocket.Connect(new IPEndPoint(ip, 9899)); //配置服务器IP与端口            receiveNewsToHandle();        }        catch        {            Console.WriteLine("连接服务器失败,请按回车键退出!");            return;        }    }    //发送消息给服务器    public static void sendNewToServer(byte[] sendArray)    {        //检查socket通道是否常通过        if (clientSocket == null)        {            loadSocketStart();        }        //发送消息给服务器        clientSocket.Send(sendArray);        //Console.WriteLine("发送socket成功");        //Debug.Log("发送socket成功");    }    //开启新线程接受消息    public static void receiveNewsToHandle()    {        readThread = new Thread(new ThreadStart(socketHandle));        readThread.Name = "SocketThread";        readThread.Start();    }    private delegate void Slider(string value);    //新线程来处理socket阻塞接收服务器推送的消息    private static void socketHandle()    {        while (true)        {            int readPosition = clientSocket.Receive(result);            byte[] buf = new byte[readPosition];            Array.Copy(result, 0, buf, 0, readPosition);            //Debug.Log("接收socket长度" + readPosition);            SocketHandler.messageReceived(buf);        }    }    /// <summary>    /// 关闭socket连接    /// </summary>    public static void closeReceiveThread()    {        if (clientSocket != null)        {            clientSocket.Close();        }        if (readThread != null && readThread.ThreadState != System.Threading.ThreadState.Running)        {            readThread.Abort();        }    }}
0 0
原创粉丝点击