基于C#實現(xiàn)TCP/UDP通信及文件傳輸?shù)氖纠?/h1>
更新時間:2026年03月12日 10:18:23 作者:yong9990
本文主要介紹了基于C#實現(xiàn)TCP/UDP通信及文件傳輸?shù)氖纠?文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
一、TCP通信實現(xiàn)
1. 服務(wù)器端(文件傳輸)
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class TcpFileServer {
private const int Port = 12345;
private const string BufferSize = 8192;
public static void Start() {
using (TcpListener listener = new TcpListener(IPAddress.Any, Port)) {
listener.Start();
Console.WriteLine($"服務(wù)器已啟動,等待連接...");
using (TcpClient client = listener.AcceptTcpClient())
using (NetworkStream stream = client.GetStream()) {
// 接收文件信息
byte[] fileInfo = new byte[1024];
int bytesRead = stream.Read(fileInfo, 0, fileInfo.Length);
string fileName = Encoding.UTF8.GetString(fileInfo, 0, bytesRead).TrimEnd('\0');
// 接收文件數(shù)據(jù)
using (FileStream fs = new FileStream($"received_{fileName}", FileMode.Create)) {
byte[] buffer = new byte[BufferSize];
int totalBytes = 0;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) {
fs.Write(buffer, 0, bytesRead);
totalBytes += bytesRead;
Console.WriteLine($"已接收: {totalBytes}字節(jié)");
}
}
}
}
}
}
2. 客戶端(文件傳輸)
public class TcpFileClient {
public static void SendFile(string filePath, string serverIp) {
using (TcpClient client = new TcpClient(serverIp, 12345))
using (NetworkStream stream = client.GetStream()) {
// 發(fā)送文件信息
byte[] fileName = Encoding.UTF8.GetBytes(Path.GetFileName(filePath));
stream.Write(fileName, 0, fileName.Length);
// 發(fā)送文件數(shù)據(jù)
using (FileStream fs = new FileStream(filePath, FileMode.Open)) {
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) {
stream.Write(buffer, 0, bytesRead);
}
}
}
}
}
二、UDP通信實現(xiàn)
1. 實時數(shù)據(jù)傳輸(無連接)
public class UdpRealTime {
private const int Port = 54321;
private static UdpClient udpServer = new UdpClient(Port);
public static void Start() {
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine("UDP服務(wù)器已啟動...");
while (true) {
byte[] received = udpServer.Receive(ref remoteEP);
string message = Encoding.UTF8.GetString(received);
Console.WriteLine($"收到來自 {remoteEP}: {message}");
// 回顯響應(yīng)
udpServer.Send(Encoding.UTF8.GetBytes("ACK"), 3, remoteEP);
}
}
}
// 客戶端
public class UdpClientApp {
public static void Send(string message, string serverIp) {
using (UdpClient client = new UdpClient()) {
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(serverIp), 54321);
byte[] data = Encoding.UTF8.GetBytes(message);
client.Send(data, data.Length, remoteEP);
// 接收回顯
IPEndPoint sendEP = new IPEndPoint(IPAddress.Any, 0);
byte[] response = client.Receive(ref sendEP);
Console.WriteLine($"服務(wù)器響應(yīng): {Encoding.UTF8.GetString(response)}");
}
}
}
三、文件傳輸增強方案
1. 斷點續(xù)傳支持
// 服務(wù)器端擴展
public class ResumableTcpServer {
public static void ResumeTransfer(TcpClient client) {
using (NetworkStream stream = client.GetStream()) {
// 獲取已傳輸字節(jié)數(shù)
byte[] resumeInfo = new byte[8];
stream.Read(resumeInfo, 0, 8);
long startPosition = BitConverter.ToInt64(resumeInfo, 0);
// 從斷點處繼續(xù)寫入
using (FileStream fs = new FileStream("resumed_file.dat", FileMode.Append)) {
fs.Seek(startPosition, SeekOrigin.Begin);
// 繼續(xù)接收數(shù)據(jù)...
}
}
}
}
// 客戶端擴展
public class ResumableTcpClient {
public static void SendWithResume(string filePath) {
FileInfo fi = new FileInfo(filePath);
long fileSize = fi.Length;
// 發(fā)送文件信息(含總大?。?
using (TcpClient client = new TcpClient("127.0.0.1", 12345)) {
NetworkStream stream = client.GetStream();
byte[] sizeBytes = BitConverter.GetBytes(fileSize);
stream.Write(sizeBytes, 0, sizeBytes.Length);
// 斷點續(xù)傳邏輯
using (FileStream fs = new FileStream(filePath, FileMode.Open)) {
fs.Seek(0, SeekOrigin.Begin); // 實際應(yīng)用中需讀取已傳輸位置
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) {
stream.Write(buffer, 0, bytesRead);
}
}
}
}
}
四、協(xié)議對比與選型建議
特性 TCP UDP 連接方式 面向連接 無連接 可靠性 保證送達、順序、完整性 不保證 傳輸效率 較低(有握手和確認(rèn)機制) 高(無額外開銷) 適用場景 文件傳輸、Web服務(wù) 實時音視頻、在線游戲、DNS查詢 典型實現(xiàn)類 TcpListener/TcpClient UdpClient
五、安全增強措施
SSL/TLS加密
using (SslStream sslStream = new SslStream(stream, false)) {
SslStream.AuthenticateAsServer(serverCertificate);
await sslStream.WriteAsync(encryptedData);
}
數(shù)據(jù)校驗
// 添加CRC32校驗
public byte[] AddChecksum(byte[] data) {
using (var crc32 = new CRC32()) {
byte[] checksum = crc32.ComputeHash(data);
return checksum.Concat(data).ToArray();
}
}
六、完整項目結(jié)構(gòu)示例
SocketApp/
├── Server/
│ ├── TcpServer.cs
│ ├── UdpServer.cs
│ └── FileTransferHandler.cs
├── Client/
│ ├── TcpClient.cs
│ ├── UdpClient.cs
│ └── FileSender.cs
├── Common/
│ ├── ProtocolParser.cs
│ └── Security/
│ └── AesEncryption.cs
└── Tests/
└── NetworkTests.cs
參考代碼 socket通訊(tcp/udp/文件傳輸?shù)龋?www.youwenfan.com/contentcsh/57550.html
七、調(diào)試與測試建議
網(wǎng)絡(luò)模擬工具
- 使用
WireShark抓包分析協(xié)議格式 - 通過
Clumsy模擬網(wǎng)絡(luò)延遲/丟包
單元測試示例
[TestClass]
public class NetworkTests {
[TestMethod]
public async Task TestTcpTransfer() {
var server = new TcpServer();
var client = new TcpClient();
await server.Start();
await client.SendFile("test.dat");
Assert.IsTrue(File.Exists("received_test.dat"));
}
}
到此這篇關(guān)于基于C#實現(xiàn)TCP/UDP通信及文件傳輸?shù)氖纠奈恼戮徒榻B到這了,更多相關(guān)C# TCP/UDP通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
-
C# DateTime.ToString根據(jù)不同語言生成相應(yīng)的時間格式
本文分享了一個按照不同國家的語言生成相應(yīng)時間格式的案例,有需要做國外網(wǎng)站或者多國語言網(wǎng)站的朋友可以參考一下。 2016-03-03
-
Unity ScrollView實現(xiàn)動態(tài)列表生成
這篇文章主要為大家詳細介紹了Unity ScrollView實現(xiàn)動態(tài)列表生成,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下 2020-04-04
-
C#代碼實現(xiàn)將PDF轉(zhuǎn)換為PDF線性化格式
PDF 線性化是一種對 PDF 文件進行優(yōu)化的方式,本文將為大家詳細介紹如何使用C#代碼將普通 PDF 轉(zhuǎn)換為線性化 PDF,感興趣的小伙伴可以參考一下 2026-04-04
最新評論
一、TCP通信實現(xiàn)
1. 服務(wù)器端(文件傳輸)
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class TcpFileServer {
private const int Port = 12345;
private const string BufferSize = 8192;
public static void Start() {
using (TcpListener listener = new TcpListener(IPAddress.Any, Port)) {
listener.Start();
Console.WriteLine($"服務(wù)器已啟動,等待連接...");
using (TcpClient client = listener.AcceptTcpClient())
using (NetworkStream stream = client.GetStream()) {
// 接收文件信息
byte[] fileInfo = new byte[1024];
int bytesRead = stream.Read(fileInfo, 0, fileInfo.Length);
string fileName = Encoding.UTF8.GetString(fileInfo, 0, bytesRead).TrimEnd('\0');
// 接收文件數(shù)據(jù)
using (FileStream fs = new FileStream($"received_{fileName}", FileMode.Create)) {
byte[] buffer = new byte[BufferSize];
int totalBytes = 0;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) {
fs.Write(buffer, 0, bytesRead);
totalBytes += bytesRead;
Console.WriteLine($"已接收: {totalBytes}字節(jié)");
}
}
}
}
}
}
2. 客戶端(文件傳輸)
public class TcpFileClient {
public static void SendFile(string filePath, string serverIp) {
using (TcpClient client = new TcpClient(serverIp, 12345))
using (NetworkStream stream = client.GetStream()) {
// 發(fā)送文件信息
byte[] fileName = Encoding.UTF8.GetBytes(Path.GetFileName(filePath));
stream.Write(fileName, 0, fileName.Length);
// 發(fā)送文件數(shù)據(jù)
using (FileStream fs = new FileStream(filePath, FileMode.Open)) {
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) {
stream.Write(buffer, 0, bytesRead);
}
}
}
}
}
二、UDP通信實現(xiàn)
1. 實時數(shù)據(jù)傳輸(無連接)
public class UdpRealTime {
private const int Port = 54321;
private static UdpClient udpServer = new UdpClient(Port);
public static void Start() {
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine("UDP服務(wù)器已啟動...");
while (true) {
byte[] received = udpServer.Receive(ref remoteEP);
string message = Encoding.UTF8.GetString(received);
Console.WriteLine($"收到來自 {remoteEP}: {message}");
// 回顯響應(yīng)
udpServer.Send(Encoding.UTF8.GetBytes("ACK"), 3, remoteEP);
}
}
}
// 客戶端
public class UdpClientApp {
public static void Send(string message, string serverIp) {
using (UdpClient client = new UdpClient()) {
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(serverIp), 54321);
byte[] data = Encoding.UTF8.GetBytes(message);
client.Send(data, data.Length, remoteEP);
// 接收回顯
IPEndPoint sendEP = new IPEndPoint(IPAddress.Any, 0);
byte[] response = client.Receive(ref sendEP);
Console.WriteLine($"服務(wù)器響應(yīng): {Encoding.UTF8.GetString(response)}");
}
}
}
三、文件傳輸增強方案
1. 斷點續(xù)傳支持
// 服務(wù)器端擴展
public class ResumableTcpServer {
public static void ResumeTransfer(TcpClient client) {
using (NetworkStream stream = client.GetStream()) {
// 獲取已傳輸字節(jié)數(shù)
byte[] resumeInfo = new byte[8];
stream.Read(resumeInfo, 0, 8);
long startPosition = BitConverter.ToInt64(resumeInfo, 0);
// 從斷點處繼續(xù)寫入
using (FileStream fs = new FileStream("resumed_file.dat", FileMode.Append)) {
fs.Seek(startPosition, SeekOrigin.Begin);
// 繼續(xù)接收數(shù)據(jù)...
}
}
}
}
// 客戶端擴展
public class ResumableTcpClient {
public static void SendWithResume(string filePath) {
FileInfo fi = new FileInfo(filePath);
long fileSize = fi.Length;
// 發(fā)送文件信息(含總大?。?
using (TcpClient client = new TcpClient("127.0.0.1", 12345)) {
NetworkStream stream = client.GetStream();
byte[] sizeBytes = BitConverter.GetBytes(fileSize);
stream.Write(sizeBytes, 0, sizeBytes.Length);
// 斷點續(xù)傳邏輯
using (FileStream fs = new FileStream(filePath, FileMode.Open)) {
fs.Seek(0, SeekOrigin.Begin); // 實際應(yīng)用中需讀取已傳輸位置
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) {
stream.Write(buffer, 0, bytesRead);
}
}
}
}
}
四、協(xié)議對比與選型建議
| 特性 | TCP | UDP |
|---|---|---|
| 連接方式 | 面向連接 | 無連接 |
| 可靠性 | 保證送達、順序、完整性 | 不保證 |
| 傳輸效率 | 較低(有握手和確認(rèn)機制) | 高(無額外開銷) |
| 適用場景 | 文件傳輸、Web服務(wù) | 實時音視頻、在線游戲、DNS查詢 |
| 典型實現(xiàn)類 | TcpListener/TcpClient | UdpClient |
五、安全增強措施
SSL/TLS加密
using (SslStream sslStream = new SslStream(stream, false)) { SslStream.AuthenticateAsServer(serverCertificate); await sslStream.WriteAsync(encryptedData); }數(shù)據(jù)校驗
// 添加CRC32校驗 public byte[] AddChecksum(byte[] data) { using (var crc32 = new CRC32()) { byte[] checksum = crc32.ComputeHash(data); return checksum.Concat(data).ToArray(); } }
六、完整項目結(jié)構(gòu)示例
SocketApp/
├── Server/
│ ├── TcpServer.cs
│ ├── UdpServer.cs
│ └── FileTransferHandler.cs
├── Client/
│ ├── TcpClient.cs
│ ├── UdpClient.cs
│ └── FileSender.cs
├── Common/
│ ├── ProtocolParser.cs
│ └── Security/
│ └── AesEncryption.cs
└── Tests/
└── NetworkTests.cs
參考代碼 socket通訊(tcp/udp/文件傳輸?shù)龋?www.youwenfan.com/contentcsh/57550.html
七、調(diào)試與測試建議
網(wǎng)絡(luò)模擬工具
- 使用
WireShark抓包分析協(xié)議格式 - 通過
Clumsy模擬網(wǎng)絡(luò)延遲/丟包
- 使用
單元測試示例
[TestClass] public class NetworkTests { [TestMethod] public async Task TestTcpTransfer() { var server = new TcpServer(); var client = new TcpClient(); await server.Start(); await client.SendFile("test.dat"); Assert.IsTrue(File.Exists("received_test.dat")); } }
到此這篇關(guān)于基于C#實現(xiàn)TCP/UDP通信及文件傳輸?shù)氖纠奈恼戮徒榻B到這了,更多相關(guān)C# TCP/UDP通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C# DateTime.ToString根據(jù)不同語言生成相應(yīng)的時間格式
本文分享了一個按照不同國家的語言生成相應(yīng)時間格式的案例,有需要做國外網(wǎng)站或者多國語言網(wǎng)站的朋友可以參考一下。2016-03-03
Unity ScrollView實現(xiàn)動態(tài)列表生成
這篇文章主要為大家詳細介紹了Unity ScrollView實現(xiàn)動態(tài)列表生成,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-04-04
C#代碼實現(xiàn)將PDF轉(zhuǎn)換為PDF線性化格式
PDF 線性化是一種對 PDF 文件進行優(yōu)化的方式,本文將為大家詳細介紹如何使用C#代碼將普通 PDF 轉(zhuǎn)換為線性化 PDF,感興趣的小伙伴可以參考一下2026-04-04

