c# 創建socket連接輔助類


using AD.SocketForm.Model;
using NLog;
using System;
using System.Net;
using System.Net.Sockets;

namespace AD.SocketForm.Service
{
    public class SocketService
    {
        private Logger _logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 創建socket
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Socket Create(HubModel model)
        {
            try
            {
                // 將IP地址字符串轉換為IPAddress對象
                IPAddress ip = IPAddress.Parse(model.IP);
                // 創建終結點EndPoint
                IPEndPoint endPoint = new IPEndPoint(ip, model.Port);
                // 創建Socket並連接到服務器
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // 連接到服務器
                socket.Connect(endPoint);

                return socket;
            }
            catch (System.Exception ex)
            {
                _logger.Error(string.Format("獲取socket異常,message:{0},stacktrace:{1}", ex.Message, ex.StackTrace));
            }
            return null;
        }

        /// <summary>
        /// 關閉socket
        /// </summary>
        /// <param name="socket"></param>
        public void Close(Socket socket)
        {
            if (socket != null)
            {
                socket.Close();
                socket = null;
            }
        }

        /// <summary>
        /// 判斷Socket是否已連接
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        public bool IsConnected(Socket socket)
        {
            if (socket == null || socket.Connected == false)
            {
                return false;
            }

            bool blockingState = socket.Blocking;
            try
            {
                byte[] tmp = new byte[1];
                socket.Blocking = false;
                socket.Send(tmp, 0, 0);
                return true;
            }
            catch (SocketException e)
            {
                // 產生 10035 == WSAEWOULDBLOCK 錯誤,說明被阻止了,但是還是連接的
                if (e.NativeErrorCode.Equals(10035))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("檢查Socket是否可連接時異常,message:{0},stacktrace:{1}", ex.Message, ex.StackTrace));
                return false;
            }
            finally
            {
                socket.Blocking = blockingState;    // 恢復狀態
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM