socket状态判断

2018-10-26  本文已影响0人  昵称违法

socket状态判断最好用心跳包机制,以下方法只能够判断其中一些状态,临时暂用,有空再好好研究。

using System.Collections;

using System.Collections.Generic;

using System.Net.Sockets;

using UnityEngine;

/// <summary>

/// socket状态侦测

/// </summary>

public class DetectSocket {

    /// <summary>

    /// 检测socket连接状态

    /// </summary>

    /// <param name="s"></param>

    /// <returns></returns>

    public static bool SocketConnected(Socket s)

    {

        // Exit if socket is null

        if (s == null)

            return false;

        bool part1 = s.Poll(1000, SelectMode.SelectRead);

        bool part2 = (s.Available == 0);

        if (part1 && part2)

            return false;

        else

        {

            try

            {

                int sentBytesCount = s.Send(new byte[1], 1, 0);//todo 改成空包

                return sentBytesCount == 1;

            }

            catch

            {

                return false;

            }

        }

    }

}

上一篇 下一篇

猜你喜欢

热点阅读