C# 当我准备好让程序结束时,如何停止 tcpClient.Connect() 进程?它只是在那里停留了 10 秒钟!

标签 c# timeout connect tcpclient

这是我的第一个问题。每当我退出程序时,tcpClient.Connect() 都会永远关闭。我尝试了很多东西,但似乎都不起作用。

看看 CreateConnection() 线程,如果客户端还没有连接……我关闭了程序,它需要很长时间才能关闭。如果已连接,它会立即关闭。我知道这可以通过某种超时技巧来完成,但我已经尝试了一些但都没有奏效。

如果可以,请提供代码示例。

此外,是否有关于 C# 的任何关于使用缓冲区读取/写入实际字节的好教程,而不是这个只执行 masterServer.writeLine() 和 masterServer.readline() 的版本,或者它们是否同样有效?

如果您看到任何其他可以帮助我改进的东西...无论如何,请继续。我正在努力自学如何做到这一点,但我没有任何帮助,所以如果你看到它,请不要让我继续做错事!!!谢谢大家!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;

namespace RemoteClient
{
    public partial class Form1 : Form
    {
        private int MyPort = 56789;
        private IPAddress myIp = IPAddress.Parse("210.232.115.79");
        private IPAddress serverIp = IPAddress.Parse("72.216.18.77"); // Master Server's IP Address
        public static TcpClient masterServer = new TcpClient();

        private StreamWriter responseWriter;
        private StreamReader commandReader;

        private Thread connectionThread;
        private Thread commandsThread;

        private bool RequestExitConnectionThread { get; set; }

        private delegate void AddMessageDelegate(string message, int category);
        private delegate void ConnectedDelegate();

        private bool isConnected { get; set; }

        public Form1()
        {
            InitializeComponent();
            isConnected = false;
        }

        private void LogMessage(string message, int category)
        {
            if (category == 1)
            {
                ListViewItem item = new ListViewItem(message);
                item.BackColor = Color.LightGreen;
                item.UseItemStyleForSubItems = true;
                Log.Items.Add(item).SubItems.Add(DateTime.Now.ToString());
            }
            if (category == 2)
            {
                ListViewItem item = new ListViewItem(message);
                item.BackColor = Color.Orange;
                item.UseItemStyleForSubItems = true;
                Log.Items.Add(item).SubItems.Add(DateTime.Now.ToString());
            }
            if (category == 3)
            {
                ListViewItem item = new ListViewItem(message);
                item.BackColor = Color.Yellow;
                item.UseItemStyleForSubItems = true;
                Log.Items.Add(item).SubItems.Add(DateTime.Now.ToString());
            }
            if (category == 0)
            {
                Log.Items.Add(message).SubItems.Add(DateTime.Now.ToString());
            }
        }

        private void Connected()
        {
            LogMessage("Found and Accepted Master Server's connection. Waiting for reply...",1);
            Status.Text = "Connected!";
            Status.ForeColor = Color.Green;

            commandsThread = new Thread(new ThreadStart(RecieveCommands));

            sendClientInfo();
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            Disconnect();
            exitButton.Enabled = false;
            exitButton.Text = "Closing...";

            if (connectionThread != null)
            {
                while (connectionThread.IsAlive)
                {
                    Application.DoEvents();
                }
            }

            this.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Connect();
        }

        private void Disconnect()
        {
            RequestExitConnectionThread = true;

            if (masterServer != null)
                masterServer.Close();

            if (connectionThread != null)
                connectionThread.Abort();

            LogMessage("Closing Client. Please wait while Program threads end.", 2);
        }

        private void Disconnected()
        {
            Status.Text = "Disconnected";
            Status.ForeColor = Color.Red;
            Connect();
        }

        private void Connect()
        {
            LogMessage("Attempting to connect to Master Server...", 1);

            connectionThread = new Thread(new ThreadStart(CreateConnection));
            connectionThread.Start();
        }

        private void CreateConnection()
        {
            int i = 1;
            bool success = false;

            while (!success)
            {
                try
                {
                    using (masterServer = new TcpClient())
                    {
                        IAsyncResult result = masterServer.BeginConnect(serverIp, MyPort, null, null);
                        success = result.AsyncWaitHandle.WaitOne(1000, false);
                    }

                    if (success)
                    {
                        BeginInvoke(new ConnectedDelegate(this.Connected), new object[] {});
                        break;
                    }
                    else
                    {
                        Thread.Sleep(2000);
                        BeginInvoke(new AddMessageDelegate(LogMessage), new object[] { "Connection Retry # " + i.ToString() + ". Master Server hasn't been started yet.", 3 });
                    }
                }
                catch
                {
                    MessageBox.Show("Error!");
                }
                i++;
            }

        }

        private void RecieveCommands()
        {
            MessageBox.Show("Hello!");
            commandReader = new StreamReader(masterServer.GetStream());

            string CommandResponse = commandReader.ReadLine();
            string Command = null;

            if (CommandResponse != null)
                MessageBox.Show("Recieved Command that was NOT null!");

            if (CommandResponse != null)
            {
                MessageBox.Show("Recieved null response!");
                BeginInvoke(new AddMessageDelegate(LogMessage), new object[] { "Disconnected From Master Server. Reason: Recieved Null response.", 1 });
                Disconnected();
            }
            else if (CommandResponse.StartsWith("0"))
            {
                MessageBox.Show("Recieved 0 as a response!");
                Command = CommandResponse.Substring(2).Trim();

                isConnected = false;
                BeginInvoke(new AddMessageDelegate(LogMessage), new object[] { "Disconnected From Master Server. Reason: " + Command, 1 });
            }
            else if (CommandResponse.StartsWith("1"))
            {
                MessageBox.Show("Recieved 1 as a response!");
                isConnected = true;
                BeginInvoke(new AddMessageDelegate(LogMessage), new object[] { "Connected to Master Server Successfully.", 1 });
            }
        }


        //************************** RESPONSE'S BELOW HERE ************************* \\

        private void sendClientInfo()
        {
            responseWriter = new StreamWriter(masterServer.GetStream());

            responseWriter.WriteLine(myIp.ToString());
            responseWriter.Flush();
        }

    }
}

最佳答案

抱歉,经过测试:不,它不使用异步等待句柄,它会阻塞进程:(

我更喜欢这个解决方案,它也会阻塞进程,但仅限于您指定的时间段,在本例中为 5 秒:

using (TcpClient tcp = new TcpClient())  
{  
    IAsyncResult ar = tcp.BeginConnect("127.0.0.1", 80, null, null);  
    System.Threading.WaitHandle wh = ar.AsyncWaitHandle;  
    try 
    {  
       if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))  
       {  
           tcp.Close();  
           throw new TimeoutException();  
       }  

        tcp.EndConnect(ar);  
    }  
    finally 
    {  
        wh.Close();  
    }  
}

发件人:http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/2281199d-cd28-4b5c-95dc-5a888a6da30d

以下示例同时使用了异步连接和异步超时控制:

var tcp = new TcpClient();
var ar = tcp.BeginConnect(Ip, Port, null, null);
Task.Factory.StartNew(() =>
{
    var wh = ar.AsyncWaitHandle;
    try
    {
        if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
        {
            // The logic to control when the connection timed out
            tcp.Close();
            throw new TimeoutException();
        }
        else
        {
            // The logic to control when the connection succeed.
            tcp.EndConnect(ar);
         }
     }
     finally
     {
         wh.Close();
     }
});

关于C# 当我准备好让程序结束时,如何停止 tcpClient.Connect() 进程?它只是在那里停留了 10 秒钟!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/795574/

相关文章:

c# - 将数百万个项目从一个存储帐户移动到另一个存储帐户

ruby - 如果工作时间太长,如何终止 ruby​​ 函数执行?

java - 为什么使用 Jsoup 连接到特定网页时会收到 404 错误?

session - 没有 cookie 的 Node.JS session

c# - 什么 R# 设置正在重新格式化这一行?

c# - 如何使用 EntityFramework 调用存储过程?

c# - Unity3D中 "AndroidJNI.FindClass"和 "AndroidJavaClass"之间有什么区别

android - ANR keyDispatchingTimedOut 报告 Google

java - 服务器长时间保持连接时http请求会超时吗?

node.js - 如何直接调用Connect中间件?