【Unity Socket】Unity Socket TCP网络编程基础

Socket通讯基本流程图

1、服务端

1.1 创建服务器端Socket对象,负责监听客户端连接

// 1.创建服务器端Socket对象,负责监听客户端连接
socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

1.2 绑定IP与端口

IPAddress ip = IPAddress.Parse(_ip);
IPEndPoint point = new IPEndPoint(ip, _port);   //创建对象端口
// 2.绑定IP与端口
socketWatch.Bind(point); 

 1.3 设置监听,设置最大监听数

// 3.设置监听,设置最大监听数
socketWatch.Listen(10);    

1.4 等待接收客户端连接(返回用于和客户端通讯的Socket)

// 4.等待接收客户端连接(返回用于和客户端通讯的Socket)
while(true)
{
    socketSend = socketWatch.Accept();           //等待接收客户端连接
}

 1.5 接收消息

// 5.接收消息
int len = socketSend.Receive(buffer);       //实际接收到的有效字节数

1.6 发送消息

// 6.发送消息
socketSend.Send(sendByte);

 1.7 关闭Socket

// 7.关闭Socket
socketWatch.Shutdown(SocketShutdown.Both);    //禁用Socket的发送和接收功能
socketWatch.Close();                          //关闭Socket连接并释放所有相关资源

socketSend.Shutdown(SocketShutdown.Both);     //禁用Socket的发送和接收功能
socketSend.Close();                           //关闭Socket连接并释放所有相关资源

2、客户端

2.1 创建一个Socket对象(和服务端进行通讯)

// 1.创建一个Socket对象(和服务端进行通讯)
socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

2.2 连接服务器

IPAddress ip = IPAddress.Parse(_ip);
IPEndPoint point = new IPEndPoint(ip, _port);
// 2.连接服务器
socketSend.Connect(point);

 2.3 接受消息

// 3.接受消息
int len = socketSend.Receive(buffer);

 2.4 发送消息

// 4.发送消息
socketSend.Send(buffer);

2.5 关闭Socket

// 5.关闭Socket
socketSend.Shutdown(SocketShutdown.Both);    //禁用Socket的发送和接收功能
socketSend.Close();                          //关闭Socket连接并释放所有相关资源

 

 3、简单实现完整代码

3.1 服务端

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;	//调用socket
using System.Text;
using System.Threading;	//调用线程
using UnityEngine;
using System.IO;

public class TCPServer : MonoBehaviour
{
    //定义变量(与GUI一致)
    private string info = "NULL";                          //状态信息
    private string recMes = "NULL";                        //接收到的信息
    private int recTimes = 0;                              //接收到的信息次数 

    private string inputIp = "127.0.0.1";                   //ip地址(本地)
    private string inputPort = "8080";                     //端口值
    private string inputMessage = "NULL";                  //用以发送的信息   

    private Socket socketWatch;                            //用以监听的套接字
    private Socket socketSend;                             //用以和客户端通信的套接字

    private bool isSendData = false;                       //是否点击发送数据按钮
    private bool clickConnectBtn = false;                  //是否点击监听按钮

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    //建立tcp通信链接
    private void ClickConnect()
    {
        try
        {
            int _port = Convert.ToInt32(inputPort);         //获取端口号(32位,4个字节)
            string _ip = inputIp;                           //获取ip地址

            Debug.Log(" ip 地址是 :" + _ip);
            Debug.Log(" 端口号是 :" + _port);

            clickConnectBtn = true;                         //点击了监听按钮,更改状态

            info = "ip地址是 : " + _ip + "端口号是 : " + _port;

            // 1.创建服务器端Socket对象,负责监听客户端连接
            socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPAddress ip = IPAddress.Parse(_ip);
            IPEndPoint point = new IPEndPoint(ip, _port);   //创建对象端口
            // 2.绑定IP与端口
            socketWatch.Bind(point);                        //绑定端口号

            Debug.Log("监听成功!");
            info = "监听成功";

            // 3.设置监听,设置最大监听数
            socketWatch.Listen(10);                         //设置监听,最大同时连接10台

            //创建监听线程
            Thread thread = new Thread(Listen);
            thread.IsBackground = true;
            thread.Start(socketWatch);
        }
        catch { }
    }

    /// <summary>
    /// 等待客户端的连接 并且创建与之通信的Socket
    /// </summary>
    void Listen(object o)
    {
        try
        {
            Socket socketWatch = o as Socket;
            while (true)
            {
                // 4.等待接收客户端连接(返回用于和客户端通讯的Socket)
                socketSend = socketWatch.Accept();           //等待接收客户端连接

                Debug.Log(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功!");
                info = socketSend.RemoteEndPoint.ToString() + "  连接成功!";

                Thread r_thread = new Thread(Received);      //开启一个新线程,执行接收消息方法
                r_thread.IsBackground = true;
                r_thread.Start(socketSend);

                Thread s_thread = new Thread(SendMessage);   //开启一个新线程,执行发送消息方法
                s_thread.IsBackground = true;
                s_thread.Start(socketSend);
            }
        }
        catch { }
    }

    // 服务器端不停的接收客户端发来的消息
    void Received(object o)
    {
        try
        {
            Socket socketSend = o as Socket;
            while (true)
            {
                byte[] buffer = new byte[1024 * 6];         //客户端连接服务器成功后,服务器接收客户端发送的消息
                // 5.接收消息
                int len = socketSend.Receive(buffer);       //实际接收到的有效字节数
                if (len == 0)
                {
                    break;
                }
                string str = Encoding.UTF8.GetString(buffer, 0, len);

                Debug.Log("接收到的消息:" + socketSend.RemoteEndPoint + ":" + str);
                recMes = str;

                recTimes++;
                info = "接收到一次数据,接收次数为:" + recTimes;
                Debug.Log("接收数据次数:" + recTimes);
            }
        }
        catch { }
    }

    // 服务器端不停的向客户端发送消息
    void SendMessage(object o)
    {
        try
        {
            Socket socketSend = o as Socket;
            while (true)
            {
                if (isSendData)
                {
                    isSendData = false;

                    byte[] sendByte = Encoding.UTF8.GetBytes(inputMessage);

                    Debug.Log("发送的数据为 :" + inputMessage);
                    Debug.Log("发送的数据字节长度 :" + sendByte.Length);

                    // 6.发送消息
                    socketSend.Send(sendByte);
                }
            }
        }
        catch { }
    }

    // 关闭连接,释放资源
    private void OnDisable()
    {
        Debug.Log("begin OnDisable()");

        if (clickConnectBtn)
        {
            try
            {
                // 7.关闭Socket
                socketWatch.Shutdown(SocketShutdown.Both);    //禁用Socket的发送和接收功能
                socketWatch.Close();                          //关闭Socket连接并释放所有相关资源

                socketSend.Shutdown(SocketShutdown.Both);     //禁用Socket的发送和接收功能
                socketSend.Close();                           //关闭Socket连接并释放所有相关资源           
            }
            catch (Exception e)
            {
                Debug.Log(e.Message);
            }
        }

        Debug.Log("end OnDisable()");
    }

    //交互界面(代码创建)
    void OnGUI()
    {
        GUI.color = Color.black;	//字体颜色

        GUI.Label(new Rect(65, 10, 80, 20), "状态信息");

        GUI.Label(new Rect(155, 10, 80, 70), info);

        GUI.Label(new Rect(65, 80, 80, 20), "接收到消息:");

        GUI.Label(new Rect(155, 80, 80, 20), recMes);

        GUI.Label(new Rect(65, 120, 80, 20), "发送的消息:");

        inputMessage = GUI.TextField(new Rect(155, 120, 100, 20), inputMessage, 20);

        GUI.Label(new Rect(65, 160, 80, 20), "本机ip地址:");

        inputIp = GUI.TextField(new Rect(155, 160, 100, 20), inputIp, 20);

        GUI.Label(new Rect(65, 200, 80, 20), "本机端口号:");

        inputPort = GUI.TextField(new Rect(155, 200, 100, 20), inputPort, 20);

        if (GUI.Button(new Rect(65, 240, 60, 20), "开始监听"))
        {
            ClickConnect();	//点击开始
        }

        if (GUI.Button(new Rect(65, 280, 60, 20), "发送数据"))
        {
            isSendData = true;	//发送数据
        }
    }
}

3.2 客户端

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO;

using System.Threading;
using UnityEngine;
using UnityEngine.UI;

public class TCPClient : MonoBehaviour
{
    public string staInfo = "NULL";             //状态信息
    public string inputIp = "127.0.0.1";   //输入ip地址
    public string inputPort = "8080";           //输入端口号
    public string inputMes = "NULL";             //发送的消息
    public int recTimes = 0;                    //接收到信息的次数
    public string recMes = "NULL";              //接收到的消息
    public Socket socketSend;                   //客户端套接字,用来链接远端服务器
    public bool clickSend = false;              //是否点击发送按钮

    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    //建立链接
    public void ClickConnect()
    {
        try
        {
            int _port = Convert.ToInt32(inputPort);             //获取端口号
            string _ip = inputIp;                               //获取ip地址

            // 1.创建一个Socket对象(和服务端进行通讯)
            socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPAddress ip = IPAddress.Parse(_ip);
            IPEndPoint point = new IPEndPoint(ip, _port);
            // 2.连接服务器
            socketSend.Connect(point);
            Debug.Log("连接成功 , " + " ip = " + ip + " port = " + _port);
            staInfo = ip + ":" + _port + "  连接成功";

            Thread r_thread = new Thread(Received);             //开启新的线程,不停的接收服务器发来的消息
            r_thread.IsBackground = true;
            r_thread.Start();

            Thread s_thread = new Thread(SendMessage);          //开启新的线程,不停的给服务器发送消息
            s_thread.IsBackground = true;
            s_thread.Start();
        }
        catch (Exception)
        {
            Debug.Log("IP或者端口号错误......");
            staInfo = "IP或者端口号错误......";
        }
    }

    /// <summary>
    /// 接收服务端返回的消息
    /// </summary>
    void Received()
    {
        while (true)
        {
            try
            {
                byte[] buffer = new byte[1024 * 6];
                //实际接收到的有效字节数
                // 3.接受消息
                int len = socketSend.Receive(buffer);
                if (len == 0)
                {
                    break;
                }

                recMes = Encoding.UTF8.GetString(buffer, 0, len);

                Debug.Log("客户端接收到的数据 : " + recMes);

                recTimes++;
                staInfo = "接收到一次数据,接收次数为 :" + recTimes;
                Debug.Log("接收次数为:" + recTimes);
            }
            catch { }
        }
    }

    /// <summary>
    /// 向服务器发送消息
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void SendMessage()
    {
        try
        {
            while (true)
            {
                if (clickSend)                              //如果点击了发送按钮
                {
                    clickSend = false;
                    string msg = inputMes;
                    byte[] buffer = new byte[1024 * 6];
                    buffer = Encoding.UTF8.GetBytes(msg);

                    // 4.发送消息
                    socketSend.Send(buffer);
                    Debug.Log("发送的数据为:" + msg);
                }
            }
        }
        catch { }
    }


    private void OnDisable()
    {
        Debug.Log("begin OnDisable()");
        if (socketSend == null) return;
        if (socketSend.Connected)
        {
            try
            {
                // 5.关闭Socket
                socketSend.Shutdown(SocketShutdown.Both);    //禁用Socket的发送和接收功能
                socketSend.Close();                          //关闭Socket连接并释放所有相关资源
            }
            catch (Exception e)
            {
                print(e.Message);
            }
        }

        Debug.Log("end OnDisable()");
    }

    //用户界面
    void OnGUI()
    {
        GUI.color = Color.black;

        GUI.Label(new Rect(65, 10, 60, 20), "状态信息");

        GUI.Label(new Rect(135, 10, 80, 60), staInfo);

        GUI.Label(new Rect(65, 70, 50, 20), "服务器ip地址");

        inputIp = GUI.TextField(new Rect(125, 70, 100, 20), inputIp, 20);

        GUI.Label(new Rect(65, 110, 50, 20), "服务器端口");

        inputPort = GUI.TextField(new Rect(125, 110, 100, 20), inputPort, 20);

        GUI.Label(new Rect(65, 150, 80, 20), "接收到消息:");

        GUI.Label(new Rect(155, 150, 80, 20), recMes);

        GUI.Label(new Rect(65, 190, 80, 20), "发送的消息:");

        inputMes = GUI.TextField(new Rect(155, 190, 100, 20), inputMes, 20);

        if (GUI.Button(new Rect(65, 230, 60, 20), "开始连接"))
        {
            ClickConnect();
        }

        if (GUI.Button(new Rect(65, 270, 60, 20), "发送信息"))
        {
            clickSend = true;
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值