■ Socket 클래스 : 소켓 연결시 시간 제한하기

------------------------------------------------------------------------------------------------------------------------

using System;

using System.Net;

using System.Net.Sockets;

 

#region 서버 연결하기 - ConnectToserver(targetIPEndPoint, port, timeOutMillisecondCount)

 

/// <summary>

/// 서버 연결하기

/// </summary>

/// <param name="targetIPEndPoint">타겟 IP 종점</param>

/// <param name="port">포트</param>

/// <param name="timeOutMillisecondCount">타임아웃(밀리초)</param>

/// <returns>소켓</returns>

public static Socket ConnectToserver(IPEndPoint targetIPEndPoint, int port, int timeOutMillisecondCount)

{

    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

 

    try

    {

        socket.Blocking = false;

 

        socket.Connect(targetIPEndPoint);

 

        return socket;

    }

    catch(SocketException socketException)

    {

        if(socketException.ErrorCode != 10035)

        {

            socket.Close();

 

            throw;

        }

 

        int timeOutMicrosecondCount = timeOutMillisecondCount * 1000;

 

        if(!socket.Poll(timeOutMicrosecondCount, SelectMode.SelectWrite))

        {

            socket.Close();

 

            throw new Exception("The host failed to connect");

        }

 

        socket.Blocking = true;

 

        return socket;

    }

}

 

#endregion

------------------------------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker