在C#中,使用TCP/IP協議傳輸大文件可以通過分塊讀取和發送文件數據的方式實現。以下是一個簡單的示例,展示了如何使用TCP/IP在C#中傳輸大文件:
首先,我們需要創建一個TCP服務器:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class TcpServer
{
public static void StartListening(int port)
{
TcpListener server = null;
try
{
server = new TcpListener(IPAddress.Any, port);
server.Start();
Console.WriteLine("Server is listening on port " + port);
while (true)
{
Console.WriteLine("Waiting for a client to connect...");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Client connected.");
NetworkStream stream = client.GetStream();
// Read file and send it in chunks
string fileName = "largefile.txt";
using (FileStream fs = File.OpenRead(fileName))
{
byte[] buffer = new byte[1024 * 1024]; // 1MB chunk size
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, bytesRead);
}
}
Console.WriteLine("File sent.");
client.Close();
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
finally
{
if (server != null)
{
server.Stop();
}
}
}
}
接下來,我們需要創建一個TCP客戶端來接收文件:
using System;
using System.IO;
using System.Net.Sockets;
class TcpClient
{
public static void Connect(string server, int port)
{
try
{
TcpClient client = new TcpClient(server, port);
NetworkStream stream = client.GetStream();
// Receive file in chunks and write it to disk
string fileName = "received_largefile.txt";
using (FileStream fs = File.Create(fileName))
{
byte[] buffer = new byte[1024 * 1024]; // 1MB chunk size
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, bytesRead);
}
}
Console.WriteLine("File received.");
client.Close();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
}
最后,我們可以在主程序中啟動服務器和客戶端:
using System;
class Program
{
static void Main(string[] args)
{
// Start server
int port = 12345;
TcpServer.StartListening(port);
// Connect client
string server = "127.0.0.1";
TcpClient.Connect(server, port);
}
}
這個示例中,服務器將大文件分成1MB大小的塊,并通過網絡流發送給客戶端。客戶端接收這些塊并將它們寫入到本地文件系統中。這種方法可以有效地傳輸大文件,而不會消耗大量內存。