C#学习第22天:网络编程

网络编程的核心概念


1. 套接字(Sockets)

  • **定义:**套接字是网络通信的基本单元,提供了在网络中进行数据交换的端点。
  • **用途:**用于TCP/UDP网络通信,支持低级别的网络数据传输。

2.协议

TCP(Transmission Control Protocol)

  • 面向连接:在传输数据之前必须建立连接。
  • 可靠性:提供顺序的数据传输,具备错误校验和重传机制,确保数据的完整性。
  • 流控制:提供拥塞控制,防止网络过载。
  • 适用于需要高可靠性和顺序性的数据传输场景。

UDP(User Datagram Protocol)

  • 无连接:不需要建立或关闭连接,数据包独立传输。
  • 不可靠:没有内置的错误校验和重传机制,数据可能会丢失、重复或无序。
  • 低延迟:因为无连接且简单的头部结构,传输速度快。
  • 适用于需要快速传输且对丢包不敏感的场景。

基本使用


使用TCP套接字

TCP服务器:

cs 复制代码
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class TcpServer
{
    public static void Main()
    {
        TcpListener server = null;

        try
        {
            Int32 port = 13000;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");
            server = new TcpListener(localAddr, port);

            server.Start();
            Console.WriteLine("Server started...");

            while (true)
            {
                Console.WriteLine("Waiting for a connection... ");
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Connected!");

                NetworkStream stream = client.GetStream();

                int i;
                byte[] bytes = new byte[256];

                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    string data = Encoding.ASCII.GetString(bytes, 0, i);
                    Console.WriteLine($"Received: {data}");

                    byte[] msg = Encoding.ASCII.GetBytes(data.ToUpper());
                    stream.Write(msg, 0, msg.Length);
                    Console.WriteLine("Sent: {0}", data.ToUpper());
                }

                client.Close();
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            server.Stop();
        }
    }
}

TCP客户端:

cs 复制代码
using System;
using System.Net.Sockets;
using System.Text;

public class TcpClientExample
{
    public static void Main()
    {
        try
        {
            Int32 port = 13000;
            TcpClient client = new TcpClient("127.0.0.1", port);

            NetworkStream stream = client.GetStream();

            Console.Write("Enter message: ");
            string message = Console.ReadLine();
            byte[] data = Encoding.ASCII.GetBytes(message);

            stream.Write(data, 0, data.Length);
            Console.WriteLine("Sent: {0}", message);

            byte[] responseData = new byte[256];
            int bytes = stream.Read(responseData, 0, responseData.Length);
            string response = Encoding.ASCII.GetString(responseData, 0, bytes);
            Console.WriteLine("Received: {0}", response);

            stream.Close();
            client.Close();
        }
        catch (ArgumentNullException e)
        {
            Console.WriteLine("ArgumentNullException: {0}", e);
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
    }
}

使用 UDP 套接字

UDP服务器:

cs 复制代码
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class UdpServer
{
    public static void Main()
    {
        UdpClient server = new UdpClient(11000);
        IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

        Console.WriteLine("UDP Server is up and waiting for packets...");

        while (true)
        {
            byte[] data = server.Receive(ref remoteEP);
            string message = Encoding.ASCII.GetString(data);
            Console.WriteLine($"Received: {message} from {remoteEP}");

            byte[] response = Encoding.ASCII.GetBytes("Echo: " + message);
            server.Send(response, response.Length, remoteEP);
        }
    }
}

UDP客户端:

cs 复制代码
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class UdpClientExample
{
    public static void Main()
    {
        UdpClient client = new UdpClient();
        client.Connect("127.0.0.1", 11000);

        Console.Write("Enter message: ");
        string message = Console.ReadLine();
        byte[] data = Encoding.ASCII.GetBytes(message);

        client.Send(data, data.Length);

        IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
        byte[] responseData = client.Receive(ref remoteEP);
        string response = Encoding.ASCII.GetString(responseData);

        Console.WriteLine("Received: {0}", response);
        client.Close();
    }
}

使用场景


1.实时通讯应用:

  • 如聊天应用、视频流等,通常使用TCP来确保数据可靠传输。

2.游戏开发:

  • 游戏开发中,UDP通常用于快速传输实时数据。

3.物联网和嵌入式设备通信:

  • 在设备之间进行数据交换,可能使用UDP来降低延迟。

希望这些信息能够帮助你更好地理解 C# 网络编程的基本知识点!如果有进一步的疑问或具体需求,请随时提出。

相关推荐
CoderCodingNo9 分钟前
【GESP】C++ 二级真题解析,[2025年12月]第一题环保能量球
开发语言·c++·算法
独好紫罗兰13 分钟前
对python的再认识-基于数据结构进行-a005-元组-CRUD
开发语言·数据结构·python
学编程的闹钟23 分钟前
95【给图片添加跳转链接】
学习
chilavert31824 分钟前
技术演进中的开发沉思-356:重排序(中)
java·开发语言
devmoon27 分钟前
为 Pallet 搭建最小化 Mock Runtime 并编写单元测试环境
开发语言·单元测试·区块链·智能合约·polkadot
EnglishJun41 分钟前
Linux系统编程(二)---学习Linux系统函数
linux·运维·学习
im_AMBER42 分钟前
Leetcode 115 分割链表 | 随机链表的复制
数据结构·学习·算法·leetcode
Coder_Boy_42 分钟前
Java开发者破局指南:跳出内卷,借AI赋能,搭建系统化知识体系
java·开发语言·人工智能·spring boot·后端·spring
Mr_Xuhhh1 小时前
介绍一下ref
开发语言·c++·算法
nbsaas-boot1 小时前
软件开发最核心的理念:接口化与组件化
开发语言