断开连接,然后重新连接客户端到服务器应用程序c#

本文关键字:服务器 应用程序 客户端 重新连接 连接 然后 断开 | 更新日期: 2023-09-27 18:13:22

我是服务器套接字的新手,当我试图创建一个简单的应用程序时,我遇到了这个问题。我可以很好地连接到服务器应用程序,也可以再次重新连接。但是当我第二次断开连接时,我得到一个错误。这是我的代码,我希望有人能帮助我理解为什么。

    private static TcpListener clientListener;
    private static Socket clientSocket;
    private static bool running = false;
    private static Thread runThread;
    static void Main(string[] args){
        writeMsg(">> Server started");
        waitForConnection();
    }
    private static void writeMsg(String msg){
        Console.WriteLine(msg);
    }
    private static void run(){
        while (running){
            try{
                byte[] prefBuffer = new byte[100];
                int bufferSize = clientSocket.Receive(prefBuffer);
                writeMsg(">> Data recieved from client");
                for (int i = 0; i < bufferSize; i++){
                    Console.Write(Convert.ToChar(prefBuffer[i]));
                }
            }
            catch{
                writeMsg("Connection Lost");
                running = false;
                clientListener.Stop();
                clientSocket.Close();
                waitForConnection();
            }
        }
        runThread.Abort();
    }
    private static void waitForConnection(){
        //This is the where the error is created and it says...
        //Cannot access disposed object.
        clientListener = new TcpListener(IPAddress.Parse("111.111.111.111"), 7414);
        clientListener.Start();
        writeMsg(">> Listening for connections...");
        try{
            clientSocket = clientListener.AcceptSocket();
            writeMsg(">> Connection established");
            running = true;
            startRunThread();
        }
        catch (Exception e){
            writeMsg(String.Format(">> Connection failed'n Error: {0}", e.Message));
        }
    }
    private static void startRunThread(){
        runThread = new Thread(new ThreadStart(run));
        runThread.Start();
    }

正如在上面代码的注释中看到的,a得到一个错误,说我不能访问一个已处置的对象,即使我重新初始化它?下面是堆栈跟踪

在System.Net.Sockets.Socket

。听(Int32积压)
在System.Net.Sockets.TcpListener。开始(Int32积压)
在System.Net.Sockets.TcpListener.Start ()
'Program.cs:第55行

断开连接,然后重新连接客户端到服务器应用程序c#

如果你想启动新的start新的线程来处理新的连接,我认为错误是由running的标志引起的。running是静态变量,在线程之间共享。每次连接丢失时,您将running设置为假,但是该线程将阻塞直到新的连接,并且running将再次变为真。这条旧线关不上。你需要打破循环,但你需要小心,因为开始新线程和关闭线程是并发的,也许第一个关闭线程和新线程已经开始完成,这将关闭应用程序,因为在某些时候,没有有效的线程在运行。

private static void run(){
    while (running){
        try{
            byte[] prefBuffer = new byte[100];
            int bufferSize = clientSocket.Receive(prefBuffer);
            writeMsg(">> Data recieved from client");
            for (int i = 0; i < bufferSize; i++){
                Console.Write(Convert.ToChar(prefBuffer[i]));
            }
        }
        catch{
            writeMsg("Connection Lost");
            running = false;
            clientListener.Stop();
            clientSocket.Close();
            waitForConnection();
            break;
        }
    }
    runThread.Abort();
}

如果你只想处理同一个运行线程中的连接,我认为错误是由两次调用startRunThread()引起的。你可以这样修改。

static void Main(string[] args)
{
    writeMsg(">> Server started");
    waitForConnection(true);
}
private static void run()
{
    while (running)
    {
        try
        {
            byte[] prefBuffer = new byte[100];
            int bufferSize = clientSocket.Receive(prefBuffer);
            if (bufferSize == 0)
            {
                throw new ApplicationException();
            }
            writeMsg(">> Data recieved from client");
            for (int i = 0; i < bufferSize; i++)
            {
                Console.Write(Convert.ToChar(prefBuffer[i]));
            }
        }
        catch
        {
            writeMsg("Connection Lost");
            running = false;
            clientSocket.Close();
            clientListener.Stop();
            waitForConnection(false);
        }
    }
    runThread.Abort();
}
private static void waitForConnection(bool newThread)
{
    //This is the where the error is created and it says...
    //Cannot access disposed object.
    clientListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 9091);
    clientListener.Start();
    writeMsg(">> Listening for connections...");
    try
    {
        clientSocket = clientListener.AcceptSocket();
        writeMsg(">> Connection established");
        running = true;
        if (newThread)
        {
            startRunThread();
        }
    }
    catch (Exception e)
    {
        writeMsg(String.Format(">> Connection failed'n Error: {0}", e.Message));
    }
}

BTW:如果客户端关闭,clientSocket.Receive(prefBuffer)将返回零,您需要处理这种情况