【随堂笔记】unity开发中Socket的用法(一,实现服务器与客户端简单的链接)

实现了简单的链接,也增加了客户端没有链接到服务器的自动重连

服务器代码

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

namespace SeverSocket
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建服务器
            Socket severSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

            //ip地址和端口号绑定
            EndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.213.54"),10001);
            //绑定服务器
            severSocket.Bind(endPoint);

            //发起监听
            severSocket.Listen(1000);

            Console.WriteLine("服务器已经启动成功!!!!");
            while (true)
            {
                Console.WriteLine("等待客户端链接");
                Socket cilentSocket = severSocket.Accept();//这里会阻塞,等待链接
                Console.WriteLine("有新的用户链接!!!!");
            }
        }
    }
}

客户端代码

using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System;
/// <summary>
/// 客户端的控制脚本
/// </summary>
public class ClientSocketController : MonoBehaviour {
    /// <summary>
    /// 链接对象
    /// </summary>
    public Socket clientSocket;
    /// <summary>
    /// ip地址
    /// </summary>
    public string ipAddress = "192.168.213.54";
    /// <summary>
    /// 端口号,这个是服务器开设的端口号
    /// </summary>
    public int portNumber = 10001;
    /// <summary>
    /// 链接间隔时间
    /// </summary>
    public float connectInterval = 1;
    /// <summary>
    /// 当前链接时间
    /// </summary>
    public float connectTime = 0;
    /// <summary>
    /// 链接次数
    /// </summary>
    public int connectCount = 0;
    /// <summary>
    /// 是否在连接中
    /// </summary>
    public bool isConnecting=false;
	void Start () {
        //调用开始连接
        ConnectedToServer();

    }
    /// <summary>
    /// 链接到服务器
    /// </summary>
    public void ConnectedToServer()
    {
        //链接次数增加
        connectCount++;
        isConnecting = true;
        Debug.Log("这是第"+connectCount+"次链接");
        //如果客户端不为空
        if (clientSocket!=null)
        {
            try
            {
                //断开连接,释放资源
                clientSocket.Disconnect(false);
                clientSocket.Close();
            }
            catch (System.Exception e)
            {
                Debug.Log(e.ToString());
            }
            
        }

        //创建新的链接(固定格式)
        clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

        //设置端口号和ip地址
        EndPoint endPoint = new IPEndPoint(IPAddress.Parse(ipAddress),portNumber);

        //发起链接
        clientSocket.BeginConnect(endPoint,OnConnectCallBack,"");
    }
    /// <summary>
    /// 开始链接的回调
    /// </summary>
    /// <param name="ar"></param>
    public void OnConnectCallBack(IAsyncResult ar)
    {
        Debug.Log("链接完成!!!!");
        if (clientSocket.Connected)
        {
            //链接成功
            Debug.Log("链接成功");
            connectCount = 0;
        }
        else
        {
            //链接失败
            Debug.Log("链接失败");
            //计时重置
            connectTime = 0;
        }
        isConnecting = false;
        //结束链接
        clientSocket.EndConnect(ar);
    }

    void Update () {
        if (clientSocket!=null && clientSocket.Connected==false)
        {
                //链接没有成功
                //计时
                connectTime += Time.deltaTime;
                if (connectTime > connectInterval && isConnecting == false)//如果时间大于链接重置时间间隔且没有链接
                {
                   if (connectCount >= 7)
                   {
                       Debug.Log("已经尝试了7次,请检查网络连接");
                       clientSocket = null;
                   }
                   else
                   {
                      //重连一次
                      ConnectedToServer();
                   }

                }


        }
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42661974/article/details/84291910