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# 网络编程的基本知识点!如果有进一步的疑问或具体需求,请随时提出。

相关推荐
李妍.1 天前
02Numpy基础(上)
开发语言·python
TheBestRucy1 天前
Python 九阳神功之贰:面向对象(下)
开发语言·python
吃着火锅x唱着歌1 天前
Effective C++ 学习笔记 条款43 学习处理模板化基类内的名称
c++·笔记·学习
AI_小站1 天前
刚面完百度的 Agent 开发岗,我才发现:世界就是个巨大的草台班子
java·开发语言·人工智能·spring·百度·langchain
felixking1 天前
C++20 协程
开发语言·c++·协程
weixin_431600441 天前
Agent Workflow 学习向:Code 节点,比模板更强的变量加工
后端·python·学习·ai·
Xuanzang Road1 天前
第 40 届学习强企玄奘路戈壁挑战赛:在绝境中重塑自我
学习
Zane1994121 天前
CAS 与原子类:Java 如何实现无锁编程
java·开发语言
码农颜1 天前
6.3 主函数流程剖析
开发语言·php
tju新生代魔迷1 天前
Python学习日记3
学习