C#,窗体程序,接收到UDP数据“shutdown”,先关闭程序再关闭电脑主机的完整代码
时间: 2024-09-20 12:05:41 浏览: 62
java代码关闭tomcat程序及出现问题解析
在C#中创建一个简单的窗体应用程序,用于接收UDP数据并根据特定的命令(如"shutdown")触发程序关闭以及计算机主机关闭的过程,可以使用`System.Net.Sockets`库处理网络通信。以下是完整的代码示例:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public partial class MainForm : Form
{
private UdpClient udpClient;
private Thread receiveThread;
public MainForm()
{
InitializeComponent();
udpClient = new UdpClient(YourUdpPort);
receiveThread = new Thread(ReceiveData);
receiveThread.Start();
}
private void ReceiveData()
{
while (true)
{
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); // Listen for incoming data
byte[] bytes = udpClient.Receive(ref remoteEP);
string receivedMessage = Encoding.ASCII.GetString(bytes).Trim();
if (receivedMessage.ToLower() == "shutdown")
{
Close(); // Close the form
Environment.Exit(0); // Exit the application
// If you want to shutdown the host as well, use a separate command or OS-specific method here (not recommended in a normal app)
// For example, on Windows you could use Process.Start("shutdown", "/s /t 0"); // This is an unsupported feature and should not be used without caution
}
}
}
protected override async void OnFormClosing(FormClosingEventArgs e)
{
await udpClient.CloseAsync(); // Close the UDP client before exiting
base.OnFormClosing(e);
}
[STAThread]
static void Main()
{
Application.Run(new MainForm());
}
}
```
在这个例子中,你需要替换`YourUdpPort`为你要监听的UDP端口。请注意,直接通过程序关闭主机功能不是一个推荐的做法,通常只适用于测试环境或者特殊控制场景。
阅读全文