基于C#編寫一個(gè)HTTP服務(wù)器和客戶端
C# WinForm 程序中實(shí)現(xiàn)一個(gè)簡(jiǎn)易的 HTTP 服務(wù)器,能夠處理 JSON 格式的 GET 和 POST 請(qǐng)求,這是一個(gè)很實(shí)用的需求,尤其適合做本地調(diào)試或輕量級(jí)服務(wù)。
實(shí)現(xiàn)思路
我會(huì)基于.NET自帶的HttpListener類來(lái)實(shí)現(xiàn)這個(gè) HTTP 服務(wù)器,它可以讓 WinForm 程序監(jiān)聽指定端口并處理 HTTP 請(qǐng)求。核心步驟包括:
- 1、初始化
HttpListener并配置監(jiān)聽地址 - 2、異步監(jiān)聽并處理客戶端請(qǐng)求
- 3、區(qū)分 GET/POST 請(qǐng)求類型
- 4、解析 / 響應(yīng) JSON 格式數(shù)據(jù)
- 5、在 WinForm 界面中控制服務(wù)器的啟動(dòng)和停止
完整代碼實(shí)現(xiàn)
以下是一個(gè)開箱即用的 WinForm 程序代碼,包含 UI 交互和完整的 HTTP 服務(wù)邏輯:
1. 首先是 Form1 的設(shè)計(jì)(Form1.Designer.cs 核心部分)
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HttpServerWinFormClient
{
public partial class Form1 : Form
{
private readonly HttpClient _httpClient;
// 默認(rèn)服務(wù)器地址
private string _baseUrl = "http://localhost:8080/";
public Form1()
{
InitializeComponent();
// 初始化HttpClient(設(shè)置超時(shí)10秒)
_httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
// 初始化界面
txtServerUrl.Text = _baseUrl;
cbxMethod.SelectedIndex = 0; // 默認(rèn)GET
// 預(yù)設(shè)JSON模板
txtRequestJson.Text = @"
{
""Id"": 1001,
""Name"": ""張三-測(cè)試中文"",
""Email"": ""zhangsan@test.com""
}";
// 清空響應(yīng)區(qū)
ClearResponse();
}
#region 界面事件
/// <summary>
/// 發(fā)送請(qǐng)求按鈕點(diǎn)擊
/// </summary>
private async void btnSend_Click(object sender, EventArgs e)
{
try
{
// 禁用按鈕,防止重復(fù)點(diǎn)擊
btnSend.Enabled = false;
ClearResponse();
_baseUrl = txtServerUrl.Text.Trim();
if (string.IsNullOrWhiteSpace(_baseUrl))
{
AppendLog("錯(cuò)誤:服務(wù)器地址不能為空!", LogLevel.Error);
btnSend.Enabled = true;
return;
}
// 記錄開始時(shí)間
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
AppendLog($"開始發(fā)送{cbxMethod.Text}請(qǐng)求到:{_baseUrl}", LogLevel.Info);
HttpResponseMessage response = null;
if (cbxMethod.Text == "GET")
{
// 發(fā)送GET請(qǐng)求
response = await _httpClient.GetAsync(_baseUrl);
}
else if (cbxMethod.Text == "POST")
{
// 驗(yàn)證POST請(qǐng)求體
string json = txtRequestJson.Text.Trim();
if (string.IsNullOrWhiteSpace(json))
{
AppendLog("錯(cuò)誤:POST請(qǐng)求體不能為空!", LogLevel.Error);
btnSend.Enabled = true;
return;
}
// 構(gòu)造POST內(nèi)容(UTF-8編碼)
var content = new StringContent(json, Encoding.UTF8, "application/json");
content.Headers.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
// 發(fā)送POST請(qǐng)求
response = await _httpClient.PostAsync(_baseUrl, content);
}
// 停止計(jì)時(shí)
stopwatch.Stop();
// 解析響應(yīng)
string responseContent = await response.Content.ReadAsStringAsync();
// 顯示響應(yīng)信息
lblStatusCode.Text = $"狀態(tài)碼:{(int)response.StatusCode} ({response.StatusCode})";
lblTimeCost.Text = $"耗時(shí):{stopwatch.ElapsedMilliseconds} ms";
txtResponseJson.Text = FormatJson(responseContent);
// 記錄日志
AppendLog($"請(qǐng)求完成 - 狀態(tài)碼:{(int)response.StatusCode},耗時(shí):{stopwatch.ElapsedMilliseconds}ms", LogLevel.Success);
}
catch (HttpRequestException ex)
{
AppendLog($"請(qǐng)求異常:{ex.Message}(請(qǐng)檢查服務(wù)器是否啟動(dòng)/地址是否正確)", LogLevel.Error);
}
catch (TaskCanceledException)
{
AppendLog("請(qǐng)求超時(shí):服務(wù)器無(wú)響應(yīng)(超時(shí)10秒)", LogLevel.Error);
}
catch (Exception ex)
{
AppendLog($"未知異常:{ex.Message}", LogLevel.Error);
}
finally
{
btnSend.Enabled = true;
}
}
/// <summary>
/// 清空響應(yīng)按鈕
/// </summary>
private void btnClear_Click(object sender, EventArgs e)
{
ClearResponse();
txtLog.Clear();
}
/// <summary>
/// 快速測(cè)試:正常POST(含中文)
/// </summary>
private void btnTestNormalPost_Click(object sender, EventArgs e)
{
cbxMethod.SelectedIndex = 1; // 切換到POST
txtRequestJson.Text = @"
{
""Id"": 1001,
""Name"": ""張三-測(cè)試中文"",
""Email"": ""zhangsan@test.com""
}";
AppendLog("已加載【正常POST(含中文)】測(cè)試模板", LogLevel.Info);
}
/// <summary>
/// 快速測(cè)試:錯(cuò)誤JSON(Id為字符串)
/// </summary>
private void btnTestErrorPost_Click(object sender, EventArgs e)
{
cbxMethod.SelectedIndex = 1; // 切換到POST
txtRequestJson.Text = @"
{
""Id"": ""1001a"",
""Name"": ""李四"",
""Email"": ""lisi@test.com""
}";
AppendLog("已加載【錯(cuò)誤JSON(Id為字符串)】測(cè)試模板", LogLevel.Info);
}
/// <summary>
/// 請(qǐng)求方法切換(隱藏/顯示POST請(qǐng)求體)
/// </summary>
private void cbxMethod_SelectedIndexChanged(object sender, EventArgs e)
{
// GET隱藏請(qǐng)求體,POST顯示
panelPostJson.Visible = (cbxMethod.Text == "POST");
}
#endregion
#region 輔助方法
/// <summary>
/// 清空響應(yīng)區(qū)域
/// </summary>
private void ClearResponse()
{
lblStatusCode.Text = "狀態(tài)碼:-";
lblTimeCost.Text = "耗時(shí):- ms";
txtResponseJson.Clear();
}
/// <summary>
/// 格式化JSON字符串(便于閱讀)
/// </summary>
private string FormatJson(string json)
{
if (string.IsNullOrWhiteSpace(json)) return "";
try
{
// 使用Newtonsoft.Json格式化(需安裝NuGet包)
dynamic parsedJson = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
return Newtonsoft.Json.JsonConvert.SerializeObject(parsedJson, Newtonsoft.Json.Formatting.Indented);
}
catch
{
// 格式化失敗則返回原字符串
return json;
}
}
/// <summary>
/// 日志級(jí)別枚舉
/// </summary>
private enum LogLevel
{
Info,
Success,
Error
}
/// <summary>
/// 追加日志(線程安全)
/// </summary>
private void AppendLog(string message, LogLevel level = LogLevel.Info)
{
if (txtLog.InvokeRequired)
{
txtLog.Invoke(new Action<string, LogLevel>(AppendLog), message, level);
return;
}
string timeStr = $"[{DateTime.Now:HH:mm:ss.fff}]";
string levelStr = level switch
{
LogLevel.Info => "[信息]",
LogLevel.Success => "[成功]",
LogLevel.Error => "[錯(cuò)誤]",
_ => "[未知]"
};
string logLine = $"{timeStr} {levelStr} {message}{Environment.NewLine}";
txtLog.AppendText(logLine);
// 自動(dòng)滾動(dòng)到最后一行
txtLog.SelectionStart = txtLog.TextLength;
txtLog.ScrollToCaret();
}
#endregion
#region 窗體設(shè)計(jì)器代碼(自動(dòng)生成)
private System.ComponentModel.IContainer components = null;
private TextBox txtServerUrl;
private Label label1;
private ComboBox cbxMethod;
private Button btnSend;
private Panel panelPostJson;
private Label label2;
private TextBox txtRequestJson;
private Label label3;
private TextBox txtResponseJson;
private Label lblStatusCode;
private Label lblTimeCost;
private Button btnClear;
private GroupBox groupBox1;
private GroupBox groupBox2;
private GroupBox groupBox3;
private TextBox txtLog;
private Button btnTestNormalPost;
private Button btnTestErrorPost;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
_httpClient?.Dispose();
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.txtServerUrl = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.cbxMethod = new System.Windows.Forms.ComboBox();
this.btnSend = new System.Windows.Forms.Button();
this.panelPostJson = new System.Windows.Forms.Panel();
this.txtRequestJson = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.txtResponseJson = new System.Windows.Forms.TextBox();
this.lblStatusCode = new System.Windows.Forms.Label();
this.lblTimeCost = new System.Windows.Forms.Label();
this.btnClear = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnTestErrorPost = new System.Windows.Forms.Button();
this.btnTestNormalPost = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.txtLog = new System.Windows.Forms.TextBox();
this.panelPostJson.SuspendLayout();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.SuspendLayout();
// txtServerUrl
this.txtServerUrl.Location = new System.Drawing.Point(85, 15);
this.txtServerUrl.Name = "txtServerUrl";
this.txtServerUrl.Size = new System.Drawing.Size(250, 23);
this.txtServerUrl.TabIndex = 0;
// label1
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(10, 18);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(69, 17);
this.label1.TabIndex = 1;
this.label1.Text = "服務(wù)器地址:";
// cbxMethod
this.cbxMethod.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbxMethod.Items.AddRange(new object[] { "GET", "POST" });
this.cbxMethod.Location = new System.Drawing.Point(341, 15);
this.cbxMethod.Name = "cbxMethod";
this.cbxMethod.Size = new System.Drawing.Size(80, 25);
this.cbxMethod.TabIndex = 2;
this.cbxMethod.SelectedIndexChanged += new System.EventHandler(this.cbxMethod_SelectedIndexChanged);
// btnSend
this.btnSend.Location = new System.Drawing.Point(427, 15);
this.btnSend.Name = "btnSend";
this.btnSend.Size = new System.Drawing.Size(80, 25);
this.btnSend.TabIndex = 3;
this.btnSend.Text = "發(fā)送請(qǐng)求";
this.btnSend.UseVisualStyleBackColor = true;
this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
// panelPostJson
this.panelPostJson.Controls.Add(this.txtRequestJson);
this.panelPostJson.Controls.Add(this.label2);
this.panelPostJson.Location = new System.Drawing.Point(10, 45);
this.panelPostJson.Name = "panelPostJson";
this.panelPostJson.Size = new System.Drawing.Size(497, 120);
this.panelPostJson.TabIndex = 4;
// txtRequestJson
this.txtRequestJson.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtRequestJson.Multiline = true;
this.txtRequestJson.Name = "txtRequestJson";
this.txtRequestJson.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtRequestJson.Size = new System.Drawing.Size(497, 95);
this.txtRequestJson.TabIndex = 1;
// label2
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(0, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(79, 17);
this.label2.TabIndex = 0;
this.label2.Text = "POST請(qǐng)求體:";
// label3
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(10, 170);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(79, 17);
this.label3.TabIndex = 5;
this.label3.Text = "響應(yīng)內(nèi)容:";
// txtResponseJson
this.txtResponseJson.Location = new System.Drawing.Point(10, 190);
this.txtResponseJson.Multiline = true;
this.txtResponseJson.Name = "txtResponseJson";
this.txtResponseJson.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtResponseJson.Size = new System.Drawing.Size(497, 120);
this.txtResponseJson.TabIndex = 6;
// lblStatusCode
this.lblStatusCode.AutoSize = true;
this.lblStatusCode.Location = new System.Drawing.Point(10, 315);
this.lblStatusCode.Name = "lblStatusCode";
this.lblStatusCode.Size = new System.Drawing.Size(53, 17);
this.lblStatusCode.TabIndex = 7;
this.lblStatusCode.Text = "狀態(tài)碼:-";
// lblTimeCost
this.lblTimeCost.AutoSize = true;
this.lblTimeCost.Location = new System.Drawing.Point(120, 315);
this.lblTimeCost.Name = "lblTimeCost";
this.lblTimeCost.Size = new System.Drawing.Size(65, 17);
this.lblTimeCost.TabIndex = 8;
this.lblTimeCost.Text = "耗時(shí):- ms";
// btnClear
this.btnClear.Location = new System.Drawing.Point(427, 310);
this.btnClear.Name = "btnClear";
this.btnClear.Size = new System.Drawing.Size(80, 25);
this.btnClear.TabIndex = 9;
this.btnClear.Text = "清空";
this.btnClear.UseVisualStyleBackColor = true;
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
// groupBox1
this.groupBox1.Controls.Add(this.btnTestErrorPost);
this.groupBox1.Controls.Add(this.btnTestNormalPost);
this.groupBox1.Controls.Add(this.txtServerUrl);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.cbxMethod);
this.groupBox1.Controls.Add(this.btnSend);
this.groupBox1.Controls.Add(this.panelPostJson);
this.groupBox1.Location = new System.Drawing.Point(10, 10);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(517, 180);
this.groupBox1.TabIndex = 10;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "請(qǐng)求配置";
// btnTestNormalPost
this.btnTestNormalPost.Location = new System.Drawing.Point(10, 170);
this.btnTestNormalPost.Name = "btnTestNormalPost";
this.btnTestNormalPost.Size = new System.Drawing.Size(150, 25);
this.btnTestNormalPost.TabIndex = 5;
this.btnTestNormalPost.Text = "快速測(cè)試:正常POST(中文)";
this.btnTestNormalPost.UseVisualStyleBackColor = true;
this.btnTestNormalPost.Click += new System.EventHandler(this.btnTestNormalPost_Click);
// btnTestErrorPost
this.btnTestErrorPost.Location = new System.Drawing.Point(166, 170);
this.btnTestErrorPost.Name = "btnTestErrorPost";
this.btnTestErrorPost.Size = new System.Drawing.Size(150, 25);
this.btnTestErrorPost.TabIndex = 6;
this.btnTestErrorPost.Text = "快速測(cè)試:錯(cuò)誤JSON(Id字符串)";
this.btnTestErrorPost.UseVisualStyleBackColor = true;
this.btnTestErrorPost.Click += new System.EventHandler(this.btnTestErrorPost_Click);
// groupBox2
this.groupBox2.Controls.Add(this.label3);
this.groupBox2.Controls.Add(this.txtResponseJson);
this.groupBox2.Controls.Add(this.lblStatusCode);
this.groupBox2.Controls.Add(this.lblTimeCost);
this.groupBox2.Controls.Add(this.btnClear);
this.groupBox2.Location = new System.Drawing.Point(10, 195);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(517, 340);
this.groupBox2.TabIndex = 11;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "響應(yīng)結(jié)果";
// groupBox3
this.groupBox3.Controls.Add(this.txtLog);
this.groupBox3.Location = new System.Drawing.Point(10, 540);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(517, 150);
this.groupBox3.TabIndex = 12;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "操作日志";
// txtLog
this.txtLog.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtLog.Multiline = true;
this.txtLog.Name = "txtLog";
this.txtLog.ReadOnly = true;
this.txtLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtLog.Size = new System.Drawing.Size(517, 125);
this.txtLog.TabIndex = 0;
// Form1
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(539, 700);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Name = "Form1";
this.Text = "HTTP服務(wù)器測(cè)試客戶端";
this.panelPostJson.ResumeLayout(false);
this.panelPostJson.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.ResumeLayout(false);
}
#endregion
}
}

APIPost軟件測(cè)試:

關(guān)鍵代碼解釋
1、HttpListener
:核心類,用于監(jiān)聽 HTTP 請(qǐng)求,支持多前綴、多請(qǐng)求處理
2、多線程處理
:監(jiān)聽線程和請(qǐng)求處理線程分離,避免阻塞 UI 線程
3、JSON 序列化 / 反序列化
:使用JavaScriptSerializer處理 JSON 數(shù)據(jù)(也可以替換為 Newtonsoft.Json,更推薦)
4、跨線程 UI 更新
:通過(guò)Control.Invoke實(shí)現(xiàn)日志的跨線程輸出,避免 WinForm 跨線程訪問(wèn)異常
5、異常處理
:完善的異常捕獲和錯(cuò)誤響應(yīng),保證服務(wù)器穩(wěn)定運(yùn)行
總結(jié)
1、該 WinForm 服務(wù)器基于HttpListener實(shí)現(xiàn),能夠穩(wěn)定處理 JSON 格式的 GET/POST 請(qǐng)求,核心是異步監(jiān)聽 + 多線程處理請(qǐng)求,避免阻塞 UI。
2、關(guān)鍵要點(diǎn):需要管理員權(quán)限運(yùn)行、正確處理跨線程 UI 更新、嚴(yán)格遵循 HTTP 響應(yīng)規(guī)范(設(shè)置 Content-Type、關(guān)閉響應(yīng)流)。
到此這篇關(guān)于基于C#編寫一個(gè)HTTP服務(wù)器和客戶端的文章就介紹到這了,更多相關(guān)C# HTTP服務(wù)器和客戶端內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c#棧變化規(guī)則圖解示例(棧的生長(zhǎng)與消亡)
多數(shù)情況下我們不需要關(guān)心棧的變化,下文會(huì)給出一個(gè)具體的示例。另外,理解棧的變化對(duì)于理解作用域也有一定的好處,因?yàn)镃#的局部變量作用域是基于棧的。2013-11-11
C#設(shè)計(jì)模式之觀察者模式實(shí)例講解
這篇文章主要介紹了C#設(shè)計(jì)模式之觀察者模式實(shí)例講解,本文詳細(xì)講解了觀察者模式的定義、優(yōu)缺點(diǎn)、代碼實(shí)例等,需要的朋友可以參考下2014-10-10
c#委托把方法當(dāng)成參數(shù)(實(shí)例講解)
本篇文章主要是對(duì)c#委托把方法當(dāng)成參數(shù)的實(shí)例代碼進(jìn)行了介紹,需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助2014-01-01

