白骑士的C#教学高级篇 3.3 网络编程

16 篇文章 0 订阅

        网络编程是现代应用程序开发中至关重要的一部分。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# 的高级特性,将使您成为更为高效和熟练的开发者。

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白骑士所长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值