客户端断开连接时关闭服务器套接字

时间:2013-01-30 11:37:58

标签: c# client-server

我有这段代码:

    private void startServer()
    {
        new Thread(() => StartListening()).Start();
    }

    void StartListening()
    {
        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        serverSocket.Bind(new IPEndPoint(0, serverPort));
        serverSocket.Listen(100);

        Accept();
    }

    void Accept()
    {
        while (true)
        {
            acceptedMessages = serverSocket.Accept();

            Buffer = new byte[acceptedMessages.SendBufferSize];
            int bytesRead = acceptedMessages.Receive(Buffer);

            byte[] formatted = new byte[bytesRead];

            for (int i = 0; i < bytesRead; i++)
            {
                formatted[i] = Buffer[i];
            }
            string command = Encoding.ASCII.GetString(formatted);
            string[] splittedCommand = command.Split(' ');

            jobsHistory.Items.Add(Encoding.ASCII.GetString(formatted));
            jobsHistory.Refresh();

            Process processToRun = new Process();
            processToRun.StartInfo.FileName = splittedCommand[0];
            processToRun.StartInfo.WorkingDirectory = Path.GetDirectoryName(splittedCommand[0]);
            processToRun.StartInfo.Arguments = "";
            for (int i = 1; i < splittedCommand.Length; i++)
            {
                processToRun.StartInfo.Arguments += " " + splittedCommand[i];
            }

            processToRun.Start();

            if (!isSocketConnected(serverSocket))
            {
                connectionStatusColor.BackColor = Color.Red;
                isConnected = false;
                startStopListnening.Text = "Listen";
                break;
            }

        }

        acceptedMessages.Shutdown(SocketShutdown.Both);

        // If you want to start listening again
        serverSocket.Shutdown(SocketShutdown.Both);
        startServer();
    }

当应用程序检测到客户端已断开连接时,我试图寻找一种安全关闭套接字的方法。

我看到了关于serverSocket.close()serverSocket.shutdown(SocketShutdown.Both);

的一些内容

但每次客户端断开连接时,应用程序都会崩溃。

有什么想法吗?

0 个答案:

没有答案