0

**i use c# this code socket connection with multi threading **

i need set time out to my socket connection telnet

    string ip = "";
    int port = 23;
    string str = "";
    IPAddress address = IPAddress.Parse(ip);
    IPEndPoint ipEndPoint = new IPEndPoint(address, port);
    Socket socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
    socket.Connect((EndPoint)ipEndPoint);
    try
    {

        byte[] numArray = new byte[1024];

        while (socket.Connected) { 

        int count = socket.Receive(numArray);
        str += Encoding.ASCII.GetString(numArray, 0, count);
            Console.WriteLine(str);
        }

        socket.Close();
    }
    catch (ArgumentNullException ex)
    {
    }

1 Answers1

0

You can either create a timer to do this or what I like to do is give the socket.connected a timeframe and base my connection of that. You'd obviously need to modify the time per your conditions, but this example has worked for me in the past.

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

// Connect using a timeout (5 seconds)

IAsyncResult result = socket.BeginConnect( iP, iPort, null, null );

bool success = result.AsyncWaitHandle.WaitOne( 5000, true );

if ( socket.Connected )
{
    socket.EndConnect( result );
}
else 
{
     //Be sure to close socket
     socket.Close();
     throw new ApplicationException("Failed to connect the server. Try again.");
}

I saw another example someone else did with timer, but I have not personally used this, so whichever you are more comfortable with. start a timer (timer_connection), if time is up, check whether socket connection is connected (if(m_clientSocket.Connected)), if not, pop up timeout error

private void connect(string ipAdd,string port)
    {
        try
        {
            SocketAsyncEventArgs e=new SocketAsyncEventArgs();


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

            IPAddress ip = IPAddress.Parse(serverIp);
            int iPortNo = System.Convert.ToInt16(serverPort);
            IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);

            //m_clientSocket.
            e.RemoteEndPoint = ipEnd;
            e.UserToken = m_clientSocket;
            e.Completed+=new EventHandler<SocketAsyncEventArgs>(e_Completed);                
            m_clientSocket.ConnectAsync(e);

            if (timer_connection != null)
            {
                timer_connection.Dispose();
            }
            else
            {
                timer_connection = new Timer();
            }
            timer_connection.Interval = 2000;
            timer_connection.Tick+=new EventHandler(timer_connection_Tick);
            timer_connection.Start();
        }
        catch (SocketException se)
        {
            lb_connectStatus.Text = "Connection Failed";
            MessageBox.Show(se.Message);
        }
    }
private void e_Completed(object sender,SocketAsyncEventArgs e)
    {
        lb_connectStatus.Text = "Connection Established";
        WaitForServerData();
    }
    private void timer_connection_Tick(object sender, EventArgs e)
    {
        if (!m_clientSocket.Connected)
        {
            MessageBox.Show("Connection Timeout");
            //m_clientSocket = null;

            timer_connection.Stop();
        }
    }
mathis1337
  • 1,426
  • 8
  • 13
  • i will try it but what is this timer_connection opejct ... i think it is like timer but timer not not have event Tick – Mohammed Ibrahim Jun 11 '20 at 17:25
  • I posted two different ways to do the same thing. You can do the above method, or below method. As for timer the tick is what happens every interval cycle and in above example that is it checks every 2 seconds for connection to be connected. – mathis1337 Jun 11 '20 at 17:38
  • There are a ton of examples here: https://stackoverflow.com/questions/1062035/how-to-configure-socket-connect-timeout – mathis1337 Jun 11 '20 at 17:42