使用winfrom编写一个web server服务端的代码
时间: 2024-05-02 17:21:05 浏览: 122
抱歉,我是一名语言模型,无法编写代码,但是我可以提供一些代码示例供您参考:
```
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WebServer
{
public partial class MainForm : Form
{
private HttpListener listener;
public MainForm()
{
InitializeComponent();
}
private async void btnStart_Click(object sender, EventArgs e)
{
listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
lblStatus.Text = "Server running...";
while (listener.IsListening)
{
var context = await listener.GetContextAsync();
ProcessRequest(context);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
listener.Stop();
lblStatus.Text = "Server stopped.";
}
private void ProcessRequest(HttpListenerContext context)
{
var request = context.Request;
var response = context.Response;
var method = request.HttpMethod;
var url = request.Url.AbsolutePath;
var query = request.Url.Query;
var content = string.Format("<html><body><h1>Method: {0}<br>URL: {1}<br>Query: {2}</h1></body></html>", method, url, query);
var buffer = Encoding.UTF8.GetBytes(content);
response.ContentLength64 = buffer.Length;
response.ContentType = "text/html";
var output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
}
}
```
这是一个使用HttpListener类创建的简单的Web服务器,它监听的端口为8080。当用户在浏览器中输入http://localhost:8080/时,服务器会返回一个包含HTTP方法、URL和查询的简单HTML页面。您可以在启动按钮的Click事件处理程序中启动服务器,然后在停止按钮的Click事件处理程序中停止服务器。
阅读全文