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);
        }
    }
    
            
           

相關推薦

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

首先我們先寫一個類,這個類是訊息抽象類 packet using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngi

HTTP議和socket協議的差別及使用

 Tcp連線:手機能夠使用聯網功能是因為手機底層實現了TCP/IP協議,可以使手機通過無線網路建立TCP連線。建立一個TCP連線需要經過“三次握手”,具體如下:第一次握手:客戶端傳送請求包到伺服器,等待伺服器確認第二次握手:伺服器響應客戶端請求,同時也傳送一個迴應包給客戶端第三次握手:客戶端收到伺服器的迴應包

HTTP議和HTTPS協議初探

generate pro 通道 lean tac spa install 對象 數據傳輸 概況 HTTP是hypertext transfer protocol(超文本傳輸協議)的簡寫。它是TCP/IP協議的一個應用層協議,用於定義WEB瀏覽器與WEB

從硬體底層通訊看http議和https協議的資料流

     嵌入式硬體與伺服器的通訊常常採用http協議或是https協議,實際上https協議就是http協議+SSL加密通訊,簡單點說就是把http協議的資料經過一定的演算法加密後傳送出去,接收方收到後再解密出來。http協議是執行在tcp協議的上一層,也就是說協

HTTP議和Https協議之間的聯絡和區別

超文字傳輸協議HTTP協議被用於在Web瀏覽器和網站伺服器之間傳遞資訊,HTTP協議以明文方式傳送內容,不提供任何方式的資料加密,如果攻擊者截取了Web瀏覽器和網站伺服器之間的傳輸報文,就可以直接讀懂其中的資訊,因此,HTTP協議不適合傳輸一些敏感資訊,比如:信用卡號、密碼

Android分別使用HTTP議和TCP協議實現上傳檔案

如果您認為本部落格不錯,讀後覺得有收穫,不妨打賞讚助我一下,讓我有動力繼續寫出高質量的部落格。 贈人玫瑰,手有餘香。分享技術,傳遞快樂。 有心課堂,傳遞的不僅僅是技術! QQ交流群:250468947 有心課堂會員,請加入VIP QQ交流

http議和https協議的區別

求和 銀行 協議 的區別 兩種 網上 安全基礎 頁面 不同的 超文本傳輸協議HTTP協議被用於在Web瀏覽器和網站服務器之間傳遞信息,HTTP協議以明文方式發送內容,不提供任何方式的數據加密,如果攻擊者截取了Web瀏覽器和網站服務器之間的傳輸報文,就可以直接讀懂其中的信息,

Java遠端下載檔案到本地(http議和ssh2協議

  Java中java.io包為我們提供了輸入流和輸出流,對檔案的讀寫基本上都依賴於這些封裝好的關於流的類中來實現。前段時間遇到了以下兩種需求:   1、與某系統對接,每天獲取最新的圖片並顯示在前端頁面。該系統提供的是一個http協議的圖片URL,本來獲取到該系統的圖片地址以後在HTML中顯示就可以了,但是該

http議和tomcat

定時 鍵值 www start 名稱 ica 停止 jvm res 1.Http協議   http:超文本傳輸協議是互聯網上應用最為廣泛的一種網絡協議.所有的ww文件都必須遵守這個標準.   http協議有http請求和http響應組成,當在瀏覽器中輸入網址訪問某個網站時,

12.2-全棧Java筆記: TCP議和UDP協議

java 區別在網絡通訊中,TCP方式就類似於撥打電話,使用該種方式進行網絡通訊時,需要建立專門的虛擬連接,然後進行可靠的數據傳輸,如果數據發送失敗,則客戶端會自動重發該數據。而UDP方式就類似於發送短信,使用這種方式進行網絡通訊時,不需要建立專門的虛擬連接,傳輸也不是很可靠,如果發送失敗則客戶端無法獲得。這

TCP/IP詳解學習筆記(3)IP協議ARP議和RARP協議

out 處理機 傳輸 包含 發送 res 這也 進行 默認 把這三個協議放到一起學習是因為這三個協議處於同一層,ARP協議用來找到目標主機的Ethernet網卡Mac地址,IP則承載要發送的消息。數據鏈路層可以從ARP得到數據的傳送信息,而從IP得到要傳輸的數據信息。   

Http議和Tomcat服務器

相關 strong ava 9.png 接收 key cookie tomcat服務器 同時 一.http協議: 超文本傳輸協議 2.組成 hhtp協議由一個請求和響應組成,當在瀏覽器中輸入網址訪問某個網站時,瀏覽器會將去請求封裝成一個hhtp請求發送給服務站點 ,服務器

HTTP議和WEB框架

英文 超文本 缺省值 通信速度 ever hand 頭部 end 接受 一、HTTP協議 一、HTTP簡介   HTTP協議是Hyper Text Transfer Protocol(超文本傳輸協議)的縮寫,是用於從萬維網(WWW:World Wide Web )服

Web的基本工作原理、HTTP議和URL說明

發送 agen mes servlet img 設置 encoding 各類 doc Web工作原理 客戶端和Web服務器通過HTTP協議進行通信。Web服務器有是也叫HTTP服務器或Web容器。HTTP協議采用的是請求/響應模式。即客戶端發起HTTP請求,web服務器接

JavaEE之Http議和Tomcat服務器

src 協議 文件目錄 服務 user 超文本傳輸協議 主機名 post 用戶 Http協議 什麽是Http協議 HTTP,超文本傳輸協議(HyperText Transfer Protocol)是互聯網上應用最為廣泛的 一種網絡協議。所有的WWW文件都必須

Http議和Tomcat服務器、Tomcat的下載與安裝

.com 運行 apache 應用 clip bubuko which 區別 版本 1、Http協議和Tomcat服務器(1)Http協議 Http請求和Http響應:有請求就有響應,有響應就有請求,這兩個是一體的;(2)Http請求: Http請求行:請求

Http議和Tomcat伺服器、Tomcat的下載與安裝

1、Http協議和Tomcat伺服器(1)Http協議 Http請求和Http響應:有請求就有響應,有響應就有請求,這兩個是一體的;(2)Http請求: Http請求行:請求方式;請求的資源;協議版本; Http請求體:post和get有區別; Http請求頭;(3)Http響應: Http響應行:狀態碼:

http議和i/o模型

http協議----基於請求報文和響應報文完成一次http事務 應用層協議格式有兩種: 文字(開發容易,但互動解析困難如http smtp),二進位制(互動解析容易,但理解起來困難memocache) 狀態碼:304 已經請求過,但是資源沒什麼改變返回304;對於get請求,只返回head,以表示資源

Http議和Servlet

文章目錄 Http協議 Http請求資料解釋 Http響應資料解析 Get 和 Post請求區別 Web資源 Servlet Hello Servlet

關於STM32的I2S通訊飛利浦議和MSB協議

最近公司一個專案要用到CODEC晶片來做語音的採集和輸出,驅動是用的STM32F405的I2S介面。之前沒有深入的瞭解過I2S的知識,只是大概的知道它是一種用於傳輸音訊資料的匯流排。本來以為沒什麼難的,實際用下來其實也沒感覺有有什麼特別的。但是還是在使用的過程中把自己坑了一把。  COD