1. 程式人生 > >關於C# 對接Http 協議和Socket 協議

關於C# 對接Http 協議和Socket 協議

首先我們先寫一個類,這個類是訊息抽象類 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);
        }
    }
    
            
           

相關推薦

no