【笔记】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("有新的用户链接!!!!");
            }
        }
    }
}

unity Socket服务端

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Net;           //IPAddress,IPEndPoint
using System.Net.Sockets;   //建立套接字socket
using System.Threading;     //建立线程thread
using System.Text;
using System.IO;
using System.Xml;
 
public class ServerSocketHandlers : MonoBehaviour
{
 
    // Start is called before the first frame update
    void Start()
    {
        openServer();
    }
 
    // Update is called once per frame
    void Update()
    {
        Send();
    }
 
    public void openServer()
    {
        try
        {
            IPAddress pAddress = IPAddress.Parse("127.0.0.1");        //IP
            IPEndPoint pEndPoint = new IPEndPoint(pAddress, 3001);    //端口号
            Socket socket_server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket_server.Bind(pEndPoint);
            socket_server.Listen(5);//设置最大连接数
            Debug.Log("监听成功");
            //创建新线程执行监听,否则会阻塞UI,导致unity无响应
            Thread thread = new Thread(listen);
            thread.IsBackground = true;
            thread.Start(socket_server);
        }
        catch (System.Exception)
        {
            throw;
        }
    }
 
    Socket socketSend;
 
    public void Send()   //要写成public,button的onclick才能捕捉到
    {
        string danmustr = "{ \"type\": \"danmu\", \"UID\": 16125790, \"uname\": \"咕之助\", \"msg\": \"";
 
        byte[] buffer = Encoding.UTF8.GetBytes(danmustr);
        socketSend.Send(buffer);
    }
 
    void listen(object o)    //不管接受还是发送都要先监听
    {
        try
        {
            Socket socketWatch = o as Socket;
            while (true)
            {
                socketSend = socketWatch.Accept();
                Debug.Log(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功");
                 
                Thread r_thread = new Thread(Received);   //可以不要这个接受,只负责发送(发送可以写在update里)
                r_thread.IsBackground = true;
                r_thread.Start(socketSend);
                 
            }
        }
        catch (System.Exception)
        {
 
            throw;
        }
    }
     
    void Received(object o)
    {
        try
        {
             Socket socketSend = o as Socket;
             while (true)
             {
                byte[] buffer = new byte[1024];
                int len = socketSend.Receive(buffer);
                if (len == 0) break;
                string str = Encoding.UTF8.GetString(buffer, 0, len);
                Debug.Log("服务器打印客户端返回消息:" + socketSend.RemoteEndPoint + ":" + str);
                 
                Send();       //也可以跟在接受的消息后再发送
                 
             }
         }
         catch (System.Exception)
        {
             throw;
         }
     }
 
}

客户端代码

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();
                   }

                }


        }
	}
}

 

转载

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值