c# - 如何关闭 TCP/IP 连接

标签 c# multithreading sockets tcp

我没有很好地学习网络。我知道 TCP/IP 的基础知识,但我面临一项任务,我必须为在同一解决方案中相互通信的多个项目管理多个线程。我在 Window 的窗体、C# 中工作,为了简单起见,我将只写需要写的内容。

这是我的客户端类,它连接到服务器,处理进出服务器的消息,以及从服务器注销。

private TcpClient ClientConnection = null;
private NetworkStream CommandStream = null;

private Thread ClientThread = null;
bool isRunning = false;

public Client()
{
    InitializeComponent();
    try
    {
        //open the connection to the command port
        ClientConnection = new TcpClient(address, Convert.ToInt32(port));

        //Get the command stream
        CommandStream = ClientConnection.GetStream();
        if (CommandStream != null)
        {
            isConnected = true;
            ClientThread = new Thread(Receive);
            isRunning = true;
            ClientThread.Start();
        }
        errorLabel.Visible = false;
    }
    catch (Exception ex)
    {
        errorLabel.Visible = true;
        errorLabel.Text = "Failed to Connect";
    }
}

private void Receive()
{
    Byte[] data = new Byte[1024];
    string message = string.Empty;
    int BytesReceived = 0;

    while (isRunning == true)
    {
        BytesReceived = CommandStream.Read(data, 0, 1024);
        message = Encoding.ASCII.GetString(data, 0, BytesReceived);

        //Do something with the message
    }
}

private void logoutButton_Click(object sender, EventArgs e)
    {
        //Do logout logic here
        errorLabel.Visible = false;

        try
        {
            if (ClientConnection != null)
            {
                Byte[] command = new Byte[1024];
                string commandStr = "SHUTDOWN";
                command = Encoding.ASCII.GetBytes(commandStr);
                CommandStream.Write(command, 0, command.GetLength(0));

                ClientConnection.Close();
                CommandStream.Close();
                isRunning = false;

                if (ClientThread.IsAlive == true)
                {
                    errorLabel.Visible = true;
                    errorLabel.Text = "Thread still alive. Failed to Disconnect";
                }
            }
        }
        catch(Exception ex)
        {
            errorLabel.Visible = true;
            errorLabel.Text = "Failed to Disconnect";
        }

    }

这是我的服务器类的进程处理函数:

private void CommandProcessHandler(Socket client)
    {
        Byte[] data = new Byte[1024];
        NetworkStream NetStream = null;

        //Exception check
        if(client.Connected == true)
            NetStream = new NetworkStream(client);

        while(bCommandListener == true)
        {
            //Read the command from the client
            int bytes = NetStream.Read(data, 0, 1024);
            string Command = Encoding.ASCII.GetString(data, 0, bytes);

            //Do something with the command
            if (Command == "SHUTDOWN")
            {
                NetStream.Close();
                client.Close();
                bCommandListener = false;
                continue;
            }
            //Display the command in the command list box
            string buttonPressed;
            string buttonLetter;

            buttonPressed = CommandDataObject.Instance.DecodeUIDFromMessage(Command);
            buttonLetter = CommandDataObject.Instance.DecodeMessageFromUID(Command);

            Command = ((client.RemoteEndPoint) as IPEndPoint).Address.ToString() + ">>>" + Command;
            UpdateCommandsListBox(Command);
        } 
    }

我确信我可以完美地启动线程,但问题在于关闭它们。这是我从未被正确教导过的一个方面,并且在学习上遇到了困难。就目前而言,我按下“注销”按钮,它应该向服务器发送一条消息以关闭,并关闭 TcpClient 和 NetworkStream。它还将保持客户端的接收线程处于事件状态的 isRunning bool 值设置为 false。

但是,就目前而言,当我执行此操作时,在第 98 行(在客户端的 Receive 函数期间,当 BytesReceived = CommandStream.Read 时)我一直收到错误,如下所示:

An unhandled exception of type 'System.IO.IOException' occurred in System.dll

Additional information: Unable to read data from the transport connection: A blocking operation was interrupted by a call to WSACancelBlockingCall.

我不确定错误指的是什么,但我已经坚持了一段时间并希望修复它。任何解决方案?

最佳答案

当您使用 NetworkStream 时,如果底层套接字在尝试读取时关闭,它将抛出 IOException,see MSDN documentation .所以你的代码非常好。您只需处理异常。

如果您直接读取套接字,当套接字关闭时您只会收到 0。

关于c# - 如何关闭 TCP/IP 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29516240/

相关文章:

c# - ASP.NET C# Ajax 调用错误

c# - 如何将字符串转换为点?

c++ - 从父类调用派生成员函数

java - X 字节后写入套接字失败

java 对象不能从不同的包源进行转换

C#串口监听器

java - notify() 调用的位置重要吗?(Java)

c++ - 如何使用 wxThreadEvent 从线程传递数据?

java - HashMap 数据未将新数据追加到 ArrayList 中

c# - 解析自定义过滤器语法的最佳方法