[Unity]简单Socket通信

7 篇文章 0 订阅

服务器端

using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using UnityEngine;
using System;

public class TcpServer
{
    //====================================================
    private Socket serverSocket;
    private byte[] buffer = new byte[4 + 1024 + 1080 * 1920];
    private Action<Data> action;

    private List<Socket> clientSockets = new List<Socket>();


    public int ClientCount
    {
        get { return clientSockets.Count; }
    }

    /// <summary>
    /// 关闭服务器
    /// </summary>
    public void Close()
    {
        foreach (var socket in clientSockets)
        {
            if (socket != null)
            {
                socket.Close();
                lock (clientSockets)
                {
                    clientSockets.Remove(socket);
                }
            }
        }

        if (serverSocket != null)
        {
            serverSocket.Close();
        }
    }

    public void RemoveAll()
    {
        foreach (var socket in clientSockets)
        {
            if (socket != null)
            {
                socket.Close();
                lock (clientSockets)
                {
                    clientSockets.Remove(socket);
                }
            }
        }
    }

    /// <summary>
    /// 关闭客户端
    /// </summary>
    /// <param name="client"></param>
    public void Close(Socket client)
    {
        lock (clientSockets)
        {
            Debug.Log("客户端关闭");
            client.Close();
            clientSockets.Remove(client);
        }
    }

    /// <summary>
    /// 断开客户端
    /// </summary>
    /// <param name="client"></param>
    public void Disconnect(Socket client)
    {
        client.Disconnect(false);
        Close(client);
    }


    /// <summary>
    /// 创建服务器
    /// </summary>
    /// <param name="userCallBack">User call back.</param>
    public void ServerInit(string ip, int port, Action<Data> callback)
    {
        try
        {
            Debug.Log("创建服务器");
            action = callback;
            buffer = new byte[4 + 1024 + 1080 * 1920];
            //实例化服务器socket
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //IP地址和端口一起称为网络节点
            IPEndPoint point = new IPEndPoint(IPAddress.Parse(ip), port);
            serverSocket.Bind(point);
            //开启监听(参数是监听客户端的数量)
            serverSocket.Listen(10);
            //开启服务器接受连接的请求
            serverSocket.BeginAccept(AcceptCallback, serverSocket);
        }
        catch (Exception)
        {
            Debug.Log("创建服务器失败");
        }
    }

    /// <summary>
    /// 接受客户端请求的回调方法
    /// </summary>
    /// <param name="ar">Ar.</param>
    void AcceptCallback(System.IAsyncResult ar)
    {
        try
        {
            Debug.Log("客户端链接");
            //serverSocket = ar.AsyncState as Socket;
            Socket workingSocket = serverSocket.EndAccept(ar);
            clientSockets.Add(workingSocket);
            Send(workingSocket, new Data(DataType.String, "Hello Client!"));
            //开启异步接收数据
            workingSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, workingSocket);
            //尾递归(继续接受其他客户端的请求)
            serverSocket.BeginAccept(AcceptCallback, serverSocket);
        }
        catch
        {
            Debug.Log("客户端链接失败");
        }
    }


    /// <summary>
    /// 服务器接收数据后的回调方法
    /// </summary>
    void ReceiveCallback(System.IAsyncResult ar)
    {
        Socket workingSocket = ar.AsyncState as Socket;
        try
        {
            //结束接受
            int count = workingSocket.EndReceive(ar);
            if (count == 0)
            {
                Close(workingSocket);
            }

            //TODO
            Data d = Message.GetData(buffer);
            if (action != null)
            {
                action(d);
            }

            //响应
            SendResponse(workingSocket, d);

        }
        catch (Exception)
        {
            Close(workingSocket);
        }

        //清空
        buffer = new byte[4 + 1024 + 1080 * 1920];
        //尾递归
        //if (workingSocket == null || !workingSocket.Connected) return;
        workingSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, workingSocket);

    }


    public void Send(Socket client, Data data)
    {
        client.Send(Message.GetBytes(data));
    }


    public void SendAll(Data data)
    {
        foreach (var socket in clientSockets)
        {
            socket.Send(Message.GetBytes(data));
        }
    }

    //响应
    private void SendResponse(Socket socket, Data data)
    {
        switch (data.type)
        {
            case DataType.Error:
                socket.Send(Message.GetBytes(new Data(DataType.String, "断开")));
                //DoNothing
                break;
            case DataType.Sucess:
                break;
            case DataType.String:
                socket.Send(Message.GetBytes(new Data(DataType.Sucess)));
                break;
            case DataType.Texture:
                socket.Send(Message.GetBytes(new Data(DataType.Sucess)));
                break;
        }
    }
}

客户端

using System;
using System.Net;
using System.Net.Sockets;
using UnityEngine;

public class TcpClient
{
    private Socket clientSocket;
    private Action<Data> action;
    private byte[] buffer = new byte[4 + 1024 + 1080 * 1920];

    public bool Connected
    {
        get
        {
            if (clientSocket == null) return false;
            return clientSocket.Connected;
        }
    }
    /// <summary>
    /// 客户端连接服务器的方法
    /// </summary>
    public void Connect(string ip, int port, Action<Data> callback)
    {
        try
        {
            if (clientSocket == null)
            {
                //实例化客户端套接字
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //根据ip地址和端口连接到服务器
                //clientSocket.Connect(IPAddress.Parse(ip), port);
                clientSocket.BeginConnect(IPAddress.Parse(ip), port, ConnectCallback, clientSocket);
            }
            else
            {
                if (!clientSocket.Connected)
                {
                    //clientSocket.Shutdown(SocketShutdown.Both);
                    //clientSocket.Disconnect(false);
                    clientSocket.Close();
                    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    //clientSocket.Connect(IPAddress.Parse(ip), port);
                    clientSocket.BeginConnect(IPAddress.Parse(ip), port, ConnectCallback, clientSocket);
                }
            }

            action = callback;
            buffer = new byte[4 + 1024 + 1080 * 1920];
            //客户端进行异步接收
            clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, clientSocket);
        }
        catch (Exception)
        {
            Debug.Log("连接服务器失败");
        }
    }

    private void ConnectCallback(System.IAsyncResult ar)
    {
        Socket workingSocket = ar.AsyncState as Socket;
        workingSocket.EndConnect(ar);
    }

    /// <summary>
    /// 客户端接受消息的回调方法
    /// </summary>
    /// <param name="ar">Ar.</param>
    private void ReceiveCallback(System.IAsyncResult ar)
    {
        //接受结果
        Socket workingSocket = ar.AsyncState as Socket;
        try
        {
            结束接受
            int count = workingSocket.EndReceive(ar);
            if (count != 0)
            {
                //TODO
                Data d = Message.GetData(buffer);
                action?.Invoke(d);

                //情空
                //尾递归
                if (clientSocket == null || clientSocket.Connected == false) return;
                buffer = new byte[4 + 1024 + 1080 * 1920];
                workingSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, workingSocket);
            }

        }
        catch (System.Exception e)
        {
        }

    }


    /// <summary>
    /// 断开连接
    /// </summary>
    public void Disconnect()
    {
        Close();
        if (clientSocket.Connected)
        {
            clientSocket.Disconnect(false);
        }
    }

    /// <summary>
    /// 关闭客户端
    /// </summary>
    public void Close()
    {
        if (clientSocket != null)
        {
            clientSocket.Close();
        }
    }


    /// <summary>
    /// 客户端发送消息
    /// </summary>
    /// <param name="msg">Message.</param>
    public void Send(Data data)
    {
        try
        {
            //客户端发送
            byte[] bytes = Message.GetBytes(data);
            clientSocket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, SendCallBack, clientSocket);
        }
        catch (Exception)
        {
            Close();
        }
    }

    private void SendCallBack(System.IAsyncResult ar)
    {
        Socket workingSocket = ar.AsyncState as Socket;
        int count = workingSocket.EndSend(ar);
    }

}

数据结构

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

public enum DataType
{
    Error,
    Sucess,
    String,
    Texture
}


public class Data
{
    public DataType type = DataType.Error;
    public string str = string.Empty;

    public byte[] typeData = new byte[4];
    public byte[] strData = new byte[1024];
    public byte[] texData = new byte[1080 * 1920];

    public Data(DataType type)
    {
        this.type = type;
        typeData = BitConverter.GetBytes((int)type);
    }

    public Data(DataType type, string str)
    {
        this.type = type;
        this.str = str;

        typeData = BitConverter.GetBytes((int)type);
        strData = Encoding.UTF8.GetBytes(str);
    }

    public Data(DataType type, byte[] t2d)
    {
        this.type = type;
        texData = t2d;
        typeData = BitConverter.GetBytes((int)type);
    }

}

public class Message
{
    public static byte[] GetBytes(Data data)
    {
        switch (data.type)
        {
            case DataType.Error:
                return data.typeData;
            case DataType.Sucess:
                return data.typeData;
            case DataType.String:
                byte[] newBytes = new byte[data.typeData.Length + data.strData.Length];
                data.typeData.CopyTo(newBytes, 0);
                data.strData.CopyTo(newBytes, data.typeData.Length);
                return newBytes;
            case DataType.Texture:
                byte[] newBytes2 = new byte[data.typeData.Length + data.texData.Length];
                data.typeData.CopyTo(newBytes2, 0);
                data.texData.CopyTo(newBytes2, data.typeData.Length);
                return newBytes2;
            default:
                return data.typeData;
        }
    }

    public static Data GetData(byte[] data)
    {
        int typeInt = BitConverter.ToInt32(data, 0);
        DataType type = (DataType)typeInt;

        switch (type)
        {
            case DataType.Error:
                return new Data(type);
            case DataType.Sucess:
                return new Data(type);
            case DataType.String:
                string str = Encoding.UTF8.GetString(data, 4, data.Length - 4);
                return new Data(type, str);
            case DataType.Texture:
                byte[] texData = new byte[data.Length - 4];
                Array.Copy(data, 4, texData, 0, data.Length - 4);
                return new Data(type, texData);
            default:
                return new Data(DataType.Error);
        }

    }

}

主线程中使用

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Linq;

public class Loom : MonoBehaviour
{
    //是否已经初始化
    static bool isInitialized;

    private static Loom _ins;
    public static Loom ins { get { Initialize(); return _ins; } }

    void Awake()
    {
        _ins = this;
        isInitialized = true;
    }

    //初始化
    public static void Initialize()
    {
        if (!isInitialized)
        {
            if (!Application.isPlaying)
                return;

            isInitialized = true;
            var obj = new GameObject("Loom");
            _ins = obj.AddComponent<Loom>();

            DontDestroyOnLoad(obj);
        }
    }

    //单个执行单元(无延迟)
    struct NoDelayedQueueItem
    {
        public Action<object> action;
        public object param;
    }
    //全部执行列表(无延迟)
    List<NoDelayedQueueItem> listNoDelayActions = new List<NoDelayedQueueItem>();


    //单个执行单元(有延迟)
    struct DelayedQueueItem
    {
        public Action<object> action;
        public object param;
        public float time;
    }
    //全部执行列表(有延迟)
    List<DelayedQueueItem> listDelayedActions = new List<DelayedQueueItem>();


    //加入到主线程执行队列(无延迟)
    public static void QueueOnMainThread(Action<object> taction, object param)
    {
        QueueOnMainThread(taction, param, 0f);
    }

    //加入到主线程执行队列(有延迟)
    public static void QueueOnMainThread(Action<object> action, object param, float time)
    {
        if (time != 0)
        {
            lock (ins.listDelayedActions)
            {
                ins.listDelayedActions.Add(new DelayedQueueItem { time = Time.time + time, action = action, param = param });
            }
        }
        else
        {
            lock (ins.listNoDelayActions)
            {
                ins.listNoDelayActions.Add(new NoDelayedQueueItem { action = action, param = param });
            }
        }
    }


    //当前执行的无延时函数链
    List<NoDelayedQueueItem> currentActions = new List<NoDelayedQueueItem>();
    //当前执行的有延时函数链
    List<DelayedQueueItem> currentDelayed = new List<DelayedQueueItem>();

    void Update()
    {
        if (listNoDelayActions.Count > 0)
        {
            lock (listNoDelayActions)
            {
                currentActions.Clear();
                currentActions.AddRange(listNoDelayActions);
                listNoDelayActions.Clear();
            }
            for (int i = 0; i < currentActions.Count; i++)
            {
                currentActions[i].action(currentActions[i].param);
            }
        }

        if (listDelayedActions.Count > 0)
        {
            lock (listDelayedActions)
            {
                currentDelayed.Clear();
                currentDelayed.AddRange(listDelayedActions.Where(d => Time.time >= d.time));
                for (int i = 0; i < currentDelayed.Count; i++)
                {
                    listDelayedActions.Remove(currentDelayed[i]);
                }
            }

            for (int i = 0; i < currentDelayed.Count; i++)
            {
                currentDelayed[i].action(currentDelayed[i].param);
            }
        }
    }

    void OnDisable()
    {
        if (_ins == this)
        {
            _ins = null;
        }
    }
}


服务器端

using UnityEngine;
using UnityEngine.UI;

public class TcpServerInstance : MonoBehaviour
{
    public Image image;
    private Data recvData;
    private TcpServer server;
    private void Awake()
    {
        Loom.Initialize();
        Application.runInBackground = true;
        server = new TcpServer();
    }
    private void Start()
    {
        server.ServerInit("127.0.0.1", 23333, (param) =>
        {
            callback(param);
        });
    }

    private void OnApplicationQuit()
    {
        server.Close();
    }

    private void OnGUI()
    {
        if (recvData != null)
        {
            GUILayout.Label(recvData.type.ToString() + ": " + recvData.str);
        }
    }

    public void callback(Data d)
    {
        Loom.QueueOnMainThread((param) =>
        {
            recvData = d;
            if (d.type == DataType.Error)
            {
                //server.Send(d.typeData);
                return;
            }
            else
            {
                if (d.type == DataType.Texture)
                {
                    Texture2D tex = new Texture2D(1080, 1920);
                    tex.LoadImage(d.texData);
                    tex.Apply();
                    Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
                    image.sprite = sprite;
                }
                //server.Send(Message.GetBytes(new Data(DataType.Sucess)));
            }

        }, d);
    }
}

客户端使用

using System.IO;
using UnityEngine;

public class TcpClientInstance : MonoBehaviour
{
    TcpClient client;

    private void Awake()
    {
        Loom.Initialize();
        Application.runInBackground = true;
        client = new TcpClient();
    }

    private void OnApplicationQuit()
    {
        client.Disconnect();
    }


    public void RecvCallback(Data data)
    {
        if (data.type == DataType.Error)
        {
            Debug.Log("发送 失败");
        }
        if (data.type == DataType.Sucess)
        {
            Debug.Log("发送 成功");
        }

        if (data.type == DataType.String)
        {
            Debug.Log(data.type.ToString() +" - " + data.str);
        } 
        
    }

    private void OnGUI()
    {
        if (GUILayout.Button("连接"))
        {
            client.Connect(Config.Ip, Config.Port, RecvCallback);
        }
    

        if (GUILayout.Button("SendStr"))
        {
            //client.Connect(Config.Ip, Config.Port, null);
            Data data = new Data(DataType.String, UnityEngine.Random.Range(0.0f, 100f).ToString());
            client.Send(data);
        }

        if (GUILayout.Button("SendTex"))
        {
            byte[] bs = File.ReadAllBytes(Application.streamingAssetsPath + "/cpic.jpg");

            Data data = new Data(DataType.Texture, bs);
            client.Send(data);
        }

        if (GUILayout.Button("断开"))
        {
            client.Disconnect();
        }
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值