Unity scoket TCP网络连接

服务端

using UnityEngine;
using System.Collections;
//引入库
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class TcpServer : MonoBehaviour
{
    Socket serverSocket; //服务器端socket
    Socket clientSocket; //客户端socket
    IPEndPoint ipEnd; //侦听端口
    string recvStr; //接收的字符串
    string sendStr; //发送的字符串
    byte[] recvData = new byte[1024]; //接收的数据,必须为字节
    byte[] sendData = new byte[1024]; //发送的数据,必须为字节
    int recvLen; //接收的数据长度
    Thread connectThread; //连接线程
	Queue<string> queue = new Queue<string>();//定义一个队列(先进先出)
    //初始化
    void InitSocket()
    {
        //定义侦听端口,侦听任何IP
        ipEnd = new IPEndPoint(IPAddress.Any, 5555);
        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //连接
        serverSocket.Bind(ipEnd);
        //开始侦听,最大10个连接
        serverSocket.Listen(10);

        connectThread = new Thread(new ThreadStart(SocketReceive));
        connectThread.Start();
    }

    //连接
    void SocketConnet()
    {
        if (clientSocket != null)
            clientSocket.Close();
        //控制台输出侦听状态
        Debug.Log("Waiting for a client");
        //一旦接受连接,创建一个客户端
        clientSocket = serverSocket.Accept();
        //获取客户端的IP和端口
        IPEndPoint ipEndClient = (IPEndPoint)clientSocket.RemoteEndPoint;
        Debug.Log("Connect" + ipEndClient.Address.ToString() + ":" + ipEndClient.Port.ToString());
        //连接成功则发送数据
        sendStr = "Hello world";
        SocketSend(sendStr);
    }

    void SocketSend(string sendStr)
    {
        //清空发送缓存
        sendData = new byte[1024];
        //数据类型转换
        sendData = Encoding.ASCII.GetBytes(sendStr);
        //发送
        clientSocket.Send(sendData, sendData.Length, SocketFlags.None);
    }

    //服务器接收
    void SocketReceive()
    {
        //连接
        SocketConnet();
        //进入接收循环
        while (true)
        {
            //对data清零
            recvData = new byte[1024];
            //获取收到的数据的长度
            recvLen = clientSocket.Receive(recvData);
            //如果收到的数据长度为0,则重连并进入下一个循环
            if (recvLen == 0)
            {
                SocketConnet();
                continue;
            }
            //输出接收到的数据
            recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);       
            queue.Enqueue(recvStr);//将消息存入队列
        }
    }

    //连接关闭
    void SocketQuit()
    {
        //先关闭客户端
        if (clientSocket != null)
            clientSocket.Close();
        //再关闭线程
        if (connectThread != null)
        {
            connectThread.Interrupt();
            connectThread.Abort();
        }
        //最后关闭服务器
        serverSocket.Close();
        Debug.Log("diconnect");
    }

    // Use this for initialization
    void Start()
    {
        InitSocket(); //在这里初始化server
    }


    // Update is called once per frame
    void Update()
    {
    		if(queue.Count>0{   			
    		   //取出收到的数据进行处理再发送出去
    		   //个人觉得还是不要在线程里面处理,毕竟如果数据庞大,还需要解析验证等环节。
               sendStr="From Server: "+queue.Dequeue();
               SocketSend(sendStr);
    		}
          
    }

    void OnApplicationQuit()
    {
        SocketQuit();
    }
}


客户端

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

public class TcpClient : MonoBehaviour
{
    string content = "Hello wolrd"; //编辑框文字

    Socket serverSocket; //服务器端socket
    IPAddress ip; //主机ip
    IPEndPoint ipEnd;
    string recvStr; //接收的字符串
    string sendStr; //发送的字符串
    byte[] recvData = new byte[1024]; //接收的数据,必须为字节
    byte[] sendData = new byte[1024]; //发送的数据,必须为字节
    int recvLen; //接收的数据长度
    Thread connectThread; //连接线程
    Queue<string> queue = new Queue<string>();//定义一个队列(先进先出)
    //初始化
    void InitSocket()
    {
        //定义服务器的IP和端口,端口与服务器对应
        ip = IPAddress.Parse("127.0.0.1");
        ipEnd = new IPEndPoint(ip, 5555);


        //开启一个线程连接,必须的,否则主线程卡死
        connectThread = new Thread(new ThreadStart(SocketReceive));
        connectThread.Start();
    }

    void SocketConnet()
    {
        if (serverSocket != null)
            serverSocket.Close();
        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        //连接
        serverSocket.Connect(ipEnd);

        //输出初次连接收到的字符串
        recvLen = serverSocket.Receive(recvData);
        recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
        Debug.Log(recvStr);
    }

    void SocketSend(string sendStr)
    {
        //清空发送缓存
        sendData = new byte[1024];
        //数据类型转换
        sendData = Encoding.ASCII.GetBytes(sendStr);
        //发送
        serverSocket.Send(sendData, sendData.Length, SocketFlags.None);
    }

    void SocketReceive()
    {
        SocketConnet();
        while (true)
        {
            recvData = new byte[1024];
            recvLen = serverSocket.Receive(recvData);
            //接收到空内容 重新连接
            if (recvLen == 0)
            {
                SocketConnet();
                continue;
            }
            recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
            queue.Enqueue(recvStr);//将消息存入队列
        }
    }

    void SocketQuit()
    {
        //关闭线程
        if (connectThread != null)
        {
            connectThread.Interrupt();
            connectThread.Abort();
        }
        //最后关闭服务器
        if (serverSocket != null)
            serverSocket.Close();
        Debug.Log("diconnect");
    }

    // Use this for initialization
    void Start()
    {
        InitSocket();
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            SocketSend(content);
        }

        if(queue.Count > 0)
        {
            //取出收到的数据进行处理再发送出去
            //个人觉得还是不要在线程里面处理,毕竟如果数据庞大,还需要解析验证等环节。
            sendStr = "From Server: " + queue.Dequeue();
            SocketSend(sendStr);
        }
    }

    //程序退出则关闭连接
    void OnApplicationQuit()
    {
        SocketQuit();
    }
}

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页