網絡編程的核心概念
1. 套接字(Sockets)
- 定義:套接字是網絡通信的基本單元,提供了在網絡中進行數據交換的端點。
- 用途:用于TCP/UDP網絡通信,支持低級別的網絡數據傳輸。
2.協議
TCP(Transmission Control Protocol)
- 面向連接:在傳輸數據之前必須建立連接。
- 可靠性:提供順序的數據傳輸,具備錯誤校驗和重傳機制,確保數據的完整性。
- 流控制:提供擁塞控制,防止網絡過載。
- 適用于需要高可靠性和順序性的數據傳輸場景。
?UDP(User Datagram Protocol)
- 無連接:不需要建立或關閉連接,數據包獨立傳輸。
- 不可靠:沒有內置的錯誤校驗和重傳機制,數據可能會丟失、重復或無序。
- 低延遲:因為無連接且簡單的頭部結構,傳輸速度快。
- 適用于需要快速傳輸且對丟包不敏感的場景。
基本使用?
使用TCP套接字
TCP服務器:
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客戶端:
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服務器:
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客戶端:
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# 網絡編程的基本知識點!如果有進一步的疑問或具體需求,請隨時提出。