多线程telnet的c#套接字连接。

问题描述 投票:0回答:1

**我用c#这个代码用多线程连接socket **。

我需要为我的套接字连接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)
    {
    }
c# multithreading sockets timeout telnet
1个回答
0
投票

你可以创建一个定时器来完成这个任务,或者我喜欢做的是给socket.connected一个时间范围,然后根据这个时间范围来连接。很明显,你需要根据你的条件修改时间,但这个例子在过去对我来说是有效的。

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.");
}

我看到另一个例子是别人用定时器做的,但我个人没有用过这个,所以不管你用哪个都比较舒服。启动一个定时器(timer_connection),如果时间到了,检查socket连接是否连接好(if(m_clientSocket.Connected)),如果没有,弹出超时错误

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();
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.