简体   繁体   English

C#中的TcpClient连接尝试

[英]TcpClient connection attempts in C#

I have a simple program. 我有一个简单的程序。 I wanted to check if the server actually is online so my users can connect to it before doing stuff, so on the form load event I have the following: 我想检查服务器是否真正在线,以便我的用户可以在做事之前连接到它,因此在表单加载事件中,我有以下内容:

 private void frmMain_Load(object sender, EventArgs e)
    {
        try
        {
            tcp.Connect("110.174.194.138", 8484);
            MessageBox.Show("siccces");
        }
        catch
        {
            MessageBox.Show("failed");
        }
        if (tcp.Connected)
        {
            //do whatever once program has connected.
        }
        else
        {
            MessageBox.Show("FAILED");
        }
    }

It all works fine when the server is online (and it can connect). 服务器处于联机状态(并且可以连接)时,一切正常。 It connects in 0.1 seconds and nothing bad happens .However, when the server is off, it attempts to reconnect about 5 times I think, which takes up to 15 seconds. 它可以在0.1秒内连接,并且没有发生任何不良情况。但是,当服务器关闭时,它会尝试重新连接大约5次(我认为是15秒)。 How can I make it attempt to connect only once so I can show a failed message instantly? 如何使它仅尝试连接一次,以便立即显示失败的消息?

Thanks. 谢谢。

Within your tcp class, you would need to modify the code to time out after a given time period. tcp类中,您需要修改代码以在给定时间段后超时。 You will have to test the connection to see if it is up within the time period given, and if not you will have to handle the results. 您将必须测试连接,以查看在给定的时间内连接是否正常,否则,您将不得不处理结果。 There are multiple ways of doing this, so just do a Google search for timeout for the socket method you are using. 有多种方法可以执行此操作,因此Google只需为您正在使用的套接字方法搜索超时即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM