当另一个套接字不再可用时,C# 套接字保持连接

C# Socket remains connected when the other socket is no longer available

我用 C# (WindowsForm) 开发了一个 client/server 应用程序来连接网络上的两台计算机。

工作原理如下:

-客户端等待服务器打开(是的,我颠倒了角色)

-当服务器打开时,客户端到达连接

问题是:如果我在连接期间关闭服务器,客户端仍然保持连接

这是一个问题,因为当我关闭服务器(并且客户端保持连接)时,如果我重新打开服务器,客户端将不再连接,因为它仍然连接 到前一个套接字(我关闭的服务器)

我希望客户端(以及服务器)能够 DETECT 当另一个套接字断开连接并且发生这种情况时,我希望客户端重新侦听传入连接(因为这是第一次)。

客户端源代码如下:

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

namespace _Client
{
    public partial class Form1 : Form
    {
        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {    
            Thread connection = new Thread(new ThreadStart(DoWork));
            connection.Start();
        }

        private void DoWork()
        {
            ListenForIncomingConnection();

            try
            {                         

                byte[] clientRequest = new byte[1024];

                while (true)
                {
                        int sizeOfRequest = client.Receive(clientRequest);
                        byte[] Request = new byte[sizeOfRequest];                            
                        Array.Copy(clientRequest, Request, sizeOfRequest);                           
                        string _stringRequest = Encoding.ASCII.GetString(Request);

                        // if the server sends a disconnecting message...
                        if(_stringRequest == "disconnecting")
                         {
                            client.Close();
                         }                     
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.ToString());                
                DoWork();
            }
        }

    private void ListenForIncomingConnection()
    {
        try
        {
            client.Connect("x.xxx.xxx.xxx", 27018);
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());
            ListenForIncomingConnection();
        }
    }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            client.Close();
        }
    }
}

当服务器断开时,客户端用client.Close()关闭连接。之后,客户端尝试重新连接到服务器,但出现此错误:无法访问已处置的对象 这是因为,在客户端尝试重新连接之前,我使用 client.Close() 关闭了连接。

如何解决?

"when I close the server"是什么意思?如果关闭服务器套接字,客户端应该会注意到。如果您在没有调用套接字上的 Close 的情况下结束服务器进程,则客户端不会注意到这一点,因为您正在跳过 TCP 的连接终止。