gpt4 book ai didi

c# - WPF 服务器应用程序

转载 作者:行者123 更新时间:2023-12-03 11:58:18 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com