在C#中實現TCP/IP文件傳輸可以通過以下步驟:
以下是一個簡單的示例代碼來實現TCP/IP文件傳輸:
服務器端代碼:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class TCPServer
{
static void Main()
{
TcpListener listener = new TcpListener(IPAddress.Any, 12345);
listener.Start();
TcpClient client = listener.AcceptTcpClient();
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int bytesRead;
using (FileStream fileStream = File.Create("received_file.txt"))
{
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, bytesRead);
}
}
client.Close();
listener.Stop();
}
}
客戶端代碼:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class TCPClient
{
static void Main()
{
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("127.0.0.1"), 12345);
NetworkStream stream = client.GetStream();
using (FileStream fileStream = File.OpenRead("file_to_send.txt"))
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, bytesRead);
}
}
client.Close();
}
}
在這個例子中,服務器端監聽端口號為12345,并在本地創建一個名為"received_file.txt"的文件來接收客戶端發送的文件數據。客戶端連接到服務器端的IP地址"127.0.0.1"和端口號12345,并發送名為"file_to_send.txt"的文件數據給服務器端。
請注意,這只是一個簡單的示例代碼,實際應用中可能需要添加錯誤處理、文件大小校驗等功能。