在C#中,處理客戶端請求通常涉及到使用網絡編程技術,如套接字(Sockets)或HTTP協議。這里我們將分別介紹如何使用這兩種方法處理客戶端請求。
要使用套接字處理客戶端請求,你需要創建一個TCP或UDP客戶端。以下是一個簡單的TCP客戶端示例:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
class TcpClientExample
{
static async Task Main()
{
string serverAddress = "127.0.0.1";
int serverPort = 12345;
using (TcpClient client = new TcpClient(serverAddress, serverPort))
{
Console.WriteLine("Connected to server.");
using (NetworkStream stream = client.GetStream())
{
using (StreamReader reader = new StreamReader(stream))
{
using (StreamWriter writer = new StreamWriter(stream))
{
// 發送請求
writer.WriteLine("Hello, server!");
await writer.FlushAsync();
// 接收響應
string response = await reader.ReadLineAsync();
Console.WriteLine("Server response: " + response);
}
}
}
}
}
}
要使用HTTP協議處理客戶端請求,你可以使用HttpClient
類。以下是一個簡單的HTTP客戶端示例:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class HttpClientExample
{
static async Task Main()
{
string serverAddress = "127.0.0.1";
int serverPort = 8080;
string requestUrl = $"{serverAddress}:{serverPort}/api/hello";
using (HttpClient client = new HttpClient())
{
try
{
// 發送請求并接收響應
HttpResponseMessage response = await client.GetAsync(requestUrl);
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Server response: " + responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("Error: " + e.Message);
}
}
}
}
請注意,這些示例僅用于演示目的。在實際應用中,你可能需要根據需求對代碼進行調整。