IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 游戏开发 -> Unity Socket -> 正文阅读

[游戏开发]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();
    }
}

  游戏开发 最新文章
6、英飞凌-AURIX-TC3XX: PWM实验之使用 GT
泛型自动装箱
CubeMax添加Rtthread操作系统 组件STM32F10
python多线程编程:如何优雅地关闭线程
数据类型隐式转换导致的阻塞
WebAPi实现多文件上传,并附带参数
from origin ‘null‘ has been blocked by
UE4 蓝图调用C++函数(附带项目工程)
Unity学习笔记(一)结构体的简单理解与应用
【Memory As a Programming Concept in C a
上一篇文章      下一篇文章      查看所有文章
加:2022-04-22 19:10:32  更:2022-04-22 19:14:49 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 13:38:46-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码