【问题标题】:c# socket connection with multi threading telnet时间:2019-05-10 标签:c#socketconnectionwithmultithreadingtelnet
【发布时间】:2020-10-01 08:42:22
【问题描述】:

**我用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】:

    您可以创建一个计时器来执行此操作,或者我喜欢给 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();
            }
        }
    

    【讨论】:

    • 我会试一试,但是这个 timer_connection opejct 是什么...我认为它就像计时器,但计时器没有事件 Tick
    • 我发布了两种不同的方法来做同样的事情。你可以做上面的方法,或者下面的方法。至于计时器,滴答是每个间隔周期发生的事情,在上面的示例中,它每 2 秒检查一次连接是否已连接。
    • 这里有很多例子:stackoverflow.com/questions/1062035/…
    猜你喜欢
    • 2020-06-15
    • 2015-06-14
    • 2011-07-08
    • 2012-02-03
    • 2017-04-15
    • 2021-07-31
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多