Socket编程(Unity简单案例,TCP协议)

时间:2021-01-25 10:20:21

服务器端

using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using Utils;

public class TCPServer : MonoBehaviour
{
    public string ipAdress;
    public int port;

    private byte[] data = new byte[1024];
    private Socket serverSocket;//服务器Socket
    private Socket client;//客户端Socket
    private Thread myThread;//启动监听线程
    private Thread receiveThread;//接收数据线程

    private List<Socket> clientSocketList = new List<Socket>();
    
    void Start()
    {
        InitSocket();

    }

    void InitSocket()
    {
        try
        {
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iPPoint = new IPEndPoint(IPAddress.Parse(ipAdress), port);
            serverSocket.Bind(iPPoint);
            serverSocket.Listen(10);
            Debug.Log("Server Running...");
            myThread = new Thread(ListenClientConnect);
            myThread.Start();

        }
        catch (System.Exception ex)
        {

            Debug.Log(ex.Message);
        }
    }

    void ListenClientConnect()
    {
        while (true)
        {
            client = serverSocket.Accept();
            clientSocketList.Add(client);

            Debug.Log("客户端:"+client.RemoteEndPoint+"连接到服务器!");
            AllSendMs("From Server:" + client.RemoteEndPoint + "客户端已连接到服务器!");

            receiveThread = new Thread(ReceiveMsg);
            receiveThread.Start(client);

        }
    }
    
    void ReceiveMsg(object clientSocket)
    {
        client = clientSocket as Socket;
        while (true)
        {
            try
            {
                int lenght = 0;
                lenght = client.Receive(data);

                if (lenght == 0 || client.Poll(100, SelectMode.SelectRead))
                {
                    string s = "客户端:" + client.RemoteEndPoint + "断开了连接!";
                    Debug.Log(s);
                    AllSendMs(s);
                    clientSocketList.Remove(client);
                    break;
                }

                string str = Encoding.UTF8.GetString(data, 0, data.Length);

                AllSendMs(str);
            }
            catch (System.Exception ex)
            {
                Debug.Log("从服务器获取数据错误" + ex.Message);
            }
        }
    }


    void AllSendMs(string ms)
    {
        for (int i = 0; i < clientSocketList.Count; i++)
        {
            clientSocketList[i].Send(Encoding.UTF8.GetBytes(ms));
        }
    }
    
    void AllSendMs(object obj)
    {
        for (int i = 0; i < clientSocketList.Count; i++)
        {
            data = obj.SerializeToByteArray();
            clientSocketList[i].Send(data, data.Length, 0);
        }
    }
    
    void OnDestroy()
    {

        try
        {
            //关闭线程
            if (myThread != null || receiveThread != null)
            {
                myThread.Interrupt();
                myThread.Abort();
                myThread = null;

                receiveThread.Interrupt();
                receiveThread.Abort();
                receiveThread = null;

            }
            //最后关闭socket
            if (serverSocket != null)
            {
                for (int i = 0; i < clientSocketList.Count; i++)
                {
                    clientSocketList[i].Close();
                    clientSocketList[i] = null;
                }

                serverSocket.Shutdown(SocketShutdown.Both);
                serverSocket.Close();
                serverSocket = null;

            }
        }
        catch (System.Exception ex)
        {
            Debug.Log(ex.Message);
        }
        print("disconnect");
    }
}

客户端

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using Utils;

public class TCPClient : MonoBehaviour
{

    public string ipAdress;
    public int port;

    private byte[] data = new byte[1024];
    private Socket clientSocket;
    private Thread receiveT;

	void Start ()
    {
        ConnectToServer();
    }

    void ConnectToServer()
    {
        try
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(IPAddress.Parse(ipAdress), port);
            Debug.Log("连接服务器成功");
            receiveT = new Thread(ReceiveMsg);
            receiveT.Start();

        }
        catch (System.Exception ex)
        {
            Debug.Log("连接服务器失败!");
            Debug.Log(ex.Message);
        }
    }

    private void ReceiveMsg()
    {
        while (true)
        {
            if (clientSocket.Connected == false)
            {
                Debug.Log("与服务器断开了连接");
                break;
            }

            int lenght = 0;
            lenght = clientSocket.Receive(data);

            string str = Encoding.UTF8.GetString(data, 0, data.Length);
            Debug.Log(str);
            
        }
    }
    
    void SendMes(string ms)
    {
        byte[] data = new byte[1024];
        data = Encoding.UTF8.GetBytes(ms);
        clientSocket.Send(data);
    }

    void SendMes(object obj)
    {
        byte[] data = new byte[1024];
        data = obj.SerializeToByteArray();
        clientSocket.Send(data, data.Length, 0);
    }
    
    void OnDestroy()
    {
        try
        {
            if (clientSocket != null)
            {
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();//关闭连接
                clientSocket = null;
            }

            if (receiveT != null)
            {
                receiveT.Interrupt();
                receiveT.Abort();
                receiveT = null;
            }

        }
        catch (Exception ex)
        {
            Debug.Log(ex.Message);
        }
    }
}