Unity Socket

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;


public class NetSocket : MonoBehaviour
{
    public static NetSocket instance;

    private void Awake()
    {
        if (instance != null && instance != this)
        {
            Destroy(gameObject);
            return;
        }

        instance = this;
        DontDestroyOnLoad(this);
        ConnectServer();
    }

    public string IP;
    public int Port;

    bool isReceived = false;
    string message;
    public Action<string> receivedToDo;

    private void Update()
    {
        if (isReceived)
        {
            isReceived = false;
            receivedToDo?.Invoke(message);
        }

        if (timecount > 0)
        {
            timecount -= Time.deltaTime;
        }
        else
        {
            timecount = 1f;
            if (isConnected)
            {
                Send("HeartBeat!");
            }
        }
    }


    float timecount = 0.25f;

    public bool isConnected = false;

    /// <summary>
    /// 连接服务器
    /// </summary>
    static Socket socket_client;

    Thread receiveThread;


    public void ConnectServer()
    {
        try
        {
            IPAddress pAddress = IPAddress.Parse(IP);
            IPEndPoint pEndPoint = new IPEndPoint(pAddress, Port);
            socket_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket_client.Connect(pEndPoint);

            isConnected = true;
            if (receiveThread == null)
            {
                receiveThread = new Thread(new ThreadStart(Received));
                receiveThread.Start();
            }
            else
            {
                receiveThread.Abort();
                receiveThread = new Thread(new ThreadStart(Received));
                receiveThread.Start();
            }
        }
        catch (System.Exception)
        {
            Debug.Log("IP端口号错误或者服务器未开启");
        }
    }


    /// <summary>
    /// 读取服务器消息
    /// </summary>
    public void Received()
    {
        while (true)
        {
            try
            {
                byte[] buffer = new byte[1024];
                int len = socket_client.Receive(buffer);

                //Debug.Log(len);
                if (len == 0) break;

                string stt = Encoding.UTF8.GetString(buffer, 0, 4);
                //Debug.Log(stt);
                //Debug.Log(int.Parse(stt));
                stt = Encoding.UTF8.GetString(buffer, 4, int.Parse(stt));
                Debug.Log("客户端打印服务器返回消息:" + socket_client.RemoteEndPoint + "  :  " + stt + "  " + stt.Length);

                message = stt;
                isReceived = true;
            }
            catch (System.Exception e)
            {
                Debug.Log(e.Message);


                if (isConnected == false)
                {
                    break;
                }
            }
        }
    }

    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="msg"></param>
    public void Send(string msg)
    {
        try
        {
            int n = 0, i = 0;
            int length = n = msg.Length;
            for (i = 0; n > 0; i++)
            {
                n /= 10;
            }

            string head = "";
            for (int j = 0; j < i; j++)
            {
                head += "0";
            }

            head += length;

            byte[] buffer = new byte[1024];
            string message = head + msg;
            // Debug.Log("[" + DateTime.Now + "]" + message);
            buffer = Encoding.UTF8.GetBytes(message);
            socket_client.Send(buffer);
        }
        catch (System.Exception)
        {
            Debug.Log("未连接");
            isConnected = false;
            ConnectServer();
        }
    }

    /// <summary>
    /// 关闭连接
    /// </summary>
    public void close()
    {
        try
        {
            socket_client.Close();
            Debug.Log("关闭客户端连接");
            isConnected = false;
            // SceneManager.LoadScene("control");
        }
        catch (System.Exception)
        {
            isConnected = false;
            Debug.Log("未连接");
        }
    }

    void OnDisable()
    {
        if (isConnected)
        {
            close();
        }
    }
}


public class ByteBuffer
{
    MemoryStream stream = null;
    BinaryWriter writer = null;
    BinaryReader reader = null;

    public ByteBuffer()
    {
        stream = new MemoryStream();
        writer = new BinaryWriter(stream);
    }

    public ByteBuffer(byte[] data)
    {
        if (data != null)
        {
            stream = new MemoryStream(data);
            reader = new BinaryReader(stream);
        }
        else
        {
            stream = new MemoryStream();
            writer = new BinaryWriter(stream);
        }
    }

    public void Close()
    {
        if (writer != null) writer.Close();
        if (reader != null) reader.Close();

        stream.Close();
        writer = null;
        reader = null;
        stream = null;
    }

    public void WriteByte(byte v)
    {
        writer.Write(v);
    }

    public void WriteInt(int v)
    {
        writer.Write((int) v);
    }

    public void WriteShort(ushort v)
    {
        writer.Write((ushort) v);
    }

    public void WriteLong(long v)
    {
        writer.Write((long) v);
    }

    public void WriteFloat(float v)
    {
        byte[] temp = BitConverter.GetBytes(v);
        Array.Reverse(temp);
        writer.Write(BitConverter.ToSingle(temp, 0));
    }

    public void WriteDouble(double v)
    {
        byte[] temp = BitConverter.GetBytes(v);
        Array.Reverse(temp);
        writer.Write(BitConverter.ToDouble(temp, 0));
    }

    public void WriteString(string v)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(v);
        writer.Write((ushort) bytes.Length);
        writer.Write(bytes);
    }

    public void WriteBytes(byte[] v)
    {
        writer.Write((int) v.Length);
        writer.Write(v);
    }

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

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

    public ushort ReadShort()
    {
        return (ushort) reader.ReadInt16();
    }

    public long ReadLong()
    {
        return (long) reader.ReadInt64();
    }

    public float ReadFloat()
    {
        byte[] temp = BitConverter.GetBytes(reader.ReadSingle());
        Array.Reverse(temp);
        return BitConverter.ToSingle(temp, 0);
    }

    public double ReadDouble()
    {
        byte[] temp = BitConverter.GetBytes(reader.ReadDouble());
        Array.Reverse(temp);
        return BitConverter.ToDouble(temp, 0);
    }

    public string ReadString()
    {
        ushort len = ReadShort();
        byte[] buffer = new byte[len];
        buffer = reader.ReadBytes(len);
        return Encoding.UTF8.GetString(buffer);
    }

    public byte[] ReadBytes()
    {
        int len = ReadInt();
        return reader.ReadBytes(len);
    }

    public byte[] ToBytes()
    {
        writer.Flush();
        return stream.ToArray();
    }

    public void Flush()
    {
        writer.Flush();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ThursdayGame

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值