unity学习(2)——网络功能实例化

1.在vs右侧asset中添加现有项,其内容如下,vs打开的不是某一个脚本,而是unity所创建的项目。

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;

public class ByteArray
{
    private MemoryStream m_Stream = new MemoryStream();
    private BinaryReader m_Reader = null;
    private BinaryWriter m_Writer = null;

    public ByteArray()
    {
        Init();
    }

    public ByteArray(MemoryStream ms)
    {
        m_Stream = ms;
        Init();
    }

    public ByteArray(byte[] buffer)
    {
        m_Stream = new MemoryStream(buffer);
        Init();
    }

    private void Init()
    {
        m_Writer = new BinaryWriter(m_Stream);
        m_Reader = new BinaryReader(m_Stream);
    }

    public int Length
    {
        get { return (int)m_Stream.Length; }
    }

    public int Postion
    {
        get { return (int)m_Stream.Position; }
        set { m_Stream.Position = value; }
    }

    public byte[] Buffer
    {
        get { return m_Stream.GetBuffer(); }
    }

    internal MemoryStream MemoryStream { get { return m_Stream; } }

    public bool ReadBoolean()
    {
        return m_Reader.ReadBoolean();
    }

    public byte ReadByte()
    {
        return m_Reader.ReadByte();
    }

    public void ReadBytes(byte[] bytes, uint offset, uint length)
    {
        byte[] tmp = m_Reader.ReadBytes((int)length);
        for (int i = 0; i < tmp.Length; i++)
            bytes[i + offset] = tmp[i];
        //m_Reader.ReadBytes(bytes, offset, length); 
    }

    public double ReadDouble()
    {
        return m_Reader.ReadDouble();
    }

    public float ReadFloat()
    {
        byte[] bytes = m_Reader.ReadBytes(4);
        byte[] invertedBytes = new byte[4];
        //Grab the bytes in reverse order from the backwards index 
        for (int i = 3, j = 0; i >= 0; i--, j++)
        {
            invertedBytes[j] = bytes[i];
        }
        float value = BitConverter.ToSingle(invertedBytes, 0);
        return value;

        // return m_Reader.ReadFloat(); 
    }

    public int ReadInt()
    {
        return m_Reader.ReadInt32();
    }

    public short ReadShort()
    {
        return m_Reader.ReadInt16();
    }

    public byte ReadUnsignedByte()
    {
        return m_Reader.ReadByte();
    }

    public uint ReadUnsignedInt()
    {
        return (uint)m_Reader.ReadInt32();
    }

    public ushort ReadUnsignedShort()
    {
        return m_Reader.ReadUInt16();
    }

    public string ReadUTF()
    {
        return m_Reader.ReadString();
    }

    public string ReadUTFBytes(uint length)
    {
        if (length == 0)
            return string.Empty;
        UTF8Encoding utf8 = new UTF8Encoding(false, true);
        byte[] encodedBytes = m_Reader.ReadBytes((int)length);
        string decodedString = utf8.GetString(encodedBytes, 0, encodedBytes.Length);
        return decodedString;
    }

    public void WriteBoolean(bool value)
    {
        m_Writer.BaseStream.WriteByte(value ? ((byte)1) : ((byte)0));
        // m_Writer.WriteBoolean(value); 
    }
    public void WriteByte(byte value)
    {
        m_Writer.BaseStream.WriteByte(value);
        // m_Writer.WriteByte(value); 
    }
    public void WriteBytes(byte[] buffer)
    {
        for (int i = 0; buffer != null && i < buffer.Length; i++)
            m_Writer.BaseStream.WriteByte(buffer[i]);
    }
    public void WriteBytes(byte[] bytes, int offset, int length)
    {
        for (int i = offset; i < offset + length; i++)
            m_Writer.BaseStream.WriteByte(bytes[i]);
    }
    public void WriteDouble(double value)
    {
        byte[] bytes = BitConverter.GetBytes(value);
        WriteBigEndian(bytes);
    }
    public void WriteFloat(float value)
    {
        byte[] bytes = BitConverter.GetBytes(value);
        WriteBigEndian(bytes);
    }
    private void WriteBigEndian(byte[] bytes)
    {
        if (bytes == null)
            return;
        for (int i = bytes.Length - 1; i >= 0; i--)
        {
            m_Writer.BaseStream.WriteByte(bytes[i]);
        }
    }

    public void WriteInt32(int value)
    {
        byte[] bytes = BitConverter.GetBytes(value);
        WriteBigEndian(bytes);
    }

    public void WriteInt(int value)
    {
        WriteInt32(value);
    }

    public void WriteShort(int value)
    {
        byte[] bytes = BitConverter.GetBytes((ushort)value);
        WriteBigEndian(bytes);
    }

    public void WriteUnsignedInt(uint value)
    {
        WriteInt32((int)value);
    }

    public void WriteUTF(string value)
    {
        UTF8Encoding utf8Encoding = new UTF8Encoding();
        int byteCount = utf8Encoding.GetByteCount(value);
        byte[] buffer = utf8Encoding.GetBytes(value);
        WriteShort(byteCount);
        if (buffer.Length > 0)
            m_Writer.Write(buffer);
    }

    public void WriteUTFBytes(string value)
    {
        UTF8Encoding utf8Encoding = new UTF8Encoding();
        byte[] buffer = utf8Encoding.GetBytes(value);
        if (buffer.Length > 0)
            m_Writer.Write(buffer);
    }

    public void WriteStringBytes(string value)
    {
        UTF8Encoding utf8Encoding = new UTF8Encoding();
        byte[] buffer = utf8Encoding.GetBytes(value);
        if (buffer.Length > 0)
        {
            m_Writer.Write(buffer.Length);
            m_Writer.Write(buffer);
        }
    }

}

2.相同的方法添加一个SocketModel类,在Scripts文件夹下新建一个Model文件夹,把这些网络通信类都放在里面。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


public class SocketModel
{
	public int type{get;set;}
	public int area{get;set;}
	public int command{get;set;}
	public string message{get;set;}
}

3.将button上的内容补充为

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using Unity.VisualScripting.FullSerializer;
using UnityEngine;
//using static ByteArray;

public class NetWorkScript : MonoBehaviour
{
    private static NetWorkScript instance;
    private static Socket socket;
    private static string ip = "127.0.0.1";
    private static int port = 8083;
    private static byte[] buff=new byte[1024];//python是达不到这个效果的 static 隔离且持久
    public static NetWorkScript getInstance()
    {
        if (instance == null)
        {
            instance = new NetWorkScript();
            init();
        }
        return instance;
    }
    public static void init()
    {
        try
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(ip, port);
            Debug.Log("success");
            socket.BeginReceive(buff,0,1024,SocketFlags.None,ReceiveCallBack,buff);//先收再回调
        }
        catch
        {
            Debug.Log("faild");
        }
    }
    public static void 照猫画虎()
    {
        Debug.Log("2");
        init();
        Debug.Log("3");
    }
    private static void ReceiveCallBack( IAsyncResult ar)//回调方法 
    {
        try
        {
            int readCount = 0;
            readCount = socket.EndReceive(ar);//ar其实就是传进来的内容
            byte[] temp = new byte[readCount];
            Buffer.BlockCopy(buff, 0, temp, 0, readCount);
            //再多新建一个
        }
        catch 
        {
            socket.Close();
            Debug.Log("net error");
        }
        socket.BeginReceive(buff, 0, 1024, SocketFlags.None, ReceiveCallBack, buff);//形成闭环
    }
    private void readMessage(byte[] message)//处理所收到的信息
    {
        MemoryStream ms = new MemoryStream(message, 0, message.Length);
        ByteArray ba = new ByteArray(ms);//这个模型是自定义的
        SocketModel model = new SocketModel();
        model.type = ba.ReadInt();
        model.area = ba.ReadInt();
        model.command = ba.ReadInt();
        int length= ba.ReadInt();
        model.message = ba.ReadUTFBytes((uint)length);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值