网络编程是现代应用程序开发中至关重要的一部分。C# 提供了一套丰富的 API 来处理基本网络通信、Web请求与响应。在本节中,我们将深入探讨这些内容,帮助您掌握如何在 C# 中进行网络编程。
基本网络通信
基本网络通信通常涉及套接字(Socket)编程。C# 提供了 ‘System.Net.Sockets‘ 命名空间来处理套接字编程,使得开发者可以创建客户端和服务器应用程序。
以下是使用 TCP 套接字创建一个简单的客户端-服务器应用程序的方法示例:
服务器端
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class Server
{
public static void Main()
{
TcpListener server = null;
try
{
int port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
server.Start();
byte[] bytes = new byte[256];
string data = null;
while (true)
{
Console.Write("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine($"Received: {data}");
data = data.ToUpper();
byte[] msg = Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
Console.WriteLine($"Sent: {data}");
}
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine($"SocketException: {e}");
}
finally
{
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
客户端
using System;
using System.Net.Sockets;
using System.Text;
public class Client
{
public static void Main()
{
try
{
Int32 port = 13000;
TcpClient client = new TcpClient("127.0.0.1", port);
NetworkStream stream = client.GetStream();
string message = "Hello, Server!";
byte[] data = Encoding.ASCII.GetBytes(message);
stream.Write(data, 0, data.Length);
Console.WriteLine($"Sent: {message}");
data = new byte[256];
string responseData = string.Empty;
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine($"Received: {responseData}");
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine($"ArgumentNullException: {e}");
}
catch (SocketException e)
{
Console.WriteLine($"SocketException: {e}");
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
在这个示例中,服务器端使用 ‘TcpListener‘ 类监听连接请求,客户端使用 ‘TcpClient‘ 类连接到服务器并发送数据。
Web请求与响应
Web请求与响应是网络编程中的常见操作。C# 提供了 ‘System.Net.Http‘ 命名空间,用于处理 HTTP 请求和响应。
发送 GET 请求
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class Program
{
private static readonly HttpClient client = new HttpClient();
public static async Task Main()
{
try
{
HttpResponseMessage response = await client.GetAsync("https://api.github.com/repos/dotnet/docs/issues");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request exception: {e.Message}");
}
}
}
在这个示例中,使用 ‘HttpClient‘ 类发送 GET 请求,并读取响应内容。
发送 POST 请求
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class Program
{
private static readonly HttpClient client = new HttpClient();
public static async Task Main()
{
var values = new Dictionary<string, string>
{
{ "username", "example" },
{ "password", "password" }
};
var content = new FormUrlEncodedContent(values);
try
{
HttpResponseMessage response = await client.PostAsync("https://example.com/api/login", content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request exception: {e.Message}");
}
}
}
在这个示例中,使用 ‘HttpClient‘ 类发送 POST 请求,并读取响应内容。
总结
在本节中,我们探讨了 C# 中进行网络编程的多种方法,包括基本网络通信和 Web 请求与响应。通过掌握这些技术,您可以开发网络应用程序,实现客户端和服务器之间的通信,处理 HTTP 请求和响应,提升应用程序的功能和性能。继续学习 C# 的高级特性,将使您成为更为高效和熟练的开发者。