c# - WPF 服务器应用程序

标签 c# wpf sockets client-server

我有一个 WPF 服务器和客户端应用程序。
当我启动服务器时,它开始收听传入的消息。但是,应用程序不能被触摸或关闭,它在监听中“卡住”了。我必须补充一点,它在处理消息等方面做了它应该做的事情。但我就是无法与表单交互。
它与异步服务器套接字有关吗?我不确定要寻找什么...

这是我的服务器代码:

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

        while (true)
        {
            Socket accepted = sck.Accept();

            Buffer = new byte[accepted.SendBufferSize];
            int bytesRead = accepted.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();
            accepted.Close();
        }
    }

最佳答案

如果这适用于 UI 线程,那么您将其捆绑在循环中。它没有机会处理任何 UI 事件。除此之外Socket.Receive是阻塞调用。

在本网站和 Google 上都有很多关于 BackgroundWorker` 类的文章。我建议你看看那些。

关于c# - WPF 服务器应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14599156/

相关文章:

c# - 接收.NET : Take until specified count or timer elapsed

c# - 这种缓慢的 WPF TextBlock 性能是否符合预期?

wpf - 循环图像旋转在 opencv 中最好的方法是什么

java - Java 中的客户端套接字编程 - 从服务器端写入客户端套接字时出现问题

c# - async/await Tcp socket 实现只接受一个连接

c# - 从字节数组转换为字符串时出现奇怪的结果

c# - 使用 dataGridView 和 BindingSource 的奇怪问题

python - 在 asyncore 中,我如何向所有或部分客户端发送数据?

c# - 无法加载文件或程序集 HttpException (0x80004005)

.net - MVVM 中的等待光标