如何在c#中通过TCP/IP发送大文件(500MB - 1GB)
本文关键字:文件 500MB 1GB IP TCP | 更新日期: 2023-09-27 18:18:46
我使用下面的代码将样本数据发送到字节流,并且工作得非常好。
使用<<p> 代码/strong>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
TcpClient tcpClient = new TcpClient("localHost", 5200);
NetworkStream networkStream = tcpClient.GetStream();
BufferedStream bs = new BufferedStream(networkStream);
//Send data to listener
byte[] dataToSend = new byte[100];
new Random().NextBytes(dataToSend);
for (int i = 0; i < 100; i++)
networkStream.Write(dataToSend, 0, dataToSend.Length);
//when the network stream is closed, it also shuts down the connection
networkStream.Close();
Console.WriteLine("Done");
Console.ReadLine();
}
}
服务器using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
TcpListener tcpListener = new TcpListener(ip, 5200);
tcpListener.Start();
Console.WriteLine("Waiting for a client to connect...");
//blocks until a client connects
Socket socketForClient = tcpListener.AcceptSocket();
Console.WriteLine("Client connected");
//Read data sent from client
NetworkStream networkStream = new NetworkStream(socketForClient);
int bytesReceived, totalReceived = 0;
byte[] receivedData = new byte[1000];
do
{
bytesReceived = networkStream.Read
(receivedData, 0, receivedData.Length);
totalReceived += bytesReceived;
}
while (bytesReceived != 0);
Console.WriteLine("Total bytes read: " + totalReceived.ToString());
socketForClient.Close();
Console.WriteLine("Client disconnected...");
Console.ReadLine();
}
}
我不知道如何用同样的方式从一个非常大的文件中发送数据。
我尝试了下面的代码,但如果文件大小是30MB或更大,它不工作。
public void SendTCP(string filePath, string IPA, Int32 PortN)
{
byte[] SendingBuffer = null;
TcpClient client = null;
lblStatus.Text = "";
NetworkStream netstream = null;
try
{
client = new TcpClient(IPA, PortN);
lblStatus.Text = "Connected to the Server...'n";
netstream = client.GetStream();
FileStream Fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
int NoOfPackets = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(Fs.Length) / Convert.ToDouble(BufferSize)));
progressBar1.Maximum = NoOfPackets;
int TotalLength = (int)Fs.Length, CurrentPacketLength, counter = 0;
for (int i = 0; i < NoOfPackets; i++)
{
if (TotalLength > BufferSize)
{
CurrentPacketLength = BufferSize;
TotalLength = TotalLength - CurrentPacketLength;
}
else
CurrentPacketLength = TotalLength;
SendingBuffer = new byte[CurrentPacketLength];
Fs.Read(SendingBuffer, 0, CurrentPacketLength);
netstream.Write(SendingBuffer, 0, (int)SendingBuffer.Length);
if (progressBar1.Value >= progressBar1.Maximum)
progressBar1.Value = progressBar1.Minimum;
progressBar1.PerformStep();
}
lblStatus.Text = lblStatus.Text + "Sent " + Fs.Length.ToString() + " bytes to the server";
Fs.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
netstream.Close();
client.Close();
}
}
应该像这样简单:
// Pass a file and send it through a socket.
static async Task SendFile(FileInfo file, Socket socket)
{
using (var networkStream = new BufferedStream(new NetworkStream(socket, false)))
using (var fileStream = file.OpenRead())
{
await fileStream.CopyToAsync(networkStream);
await networkStream.FlushAsync();
}
}
// Pass a socket and read the content to copy it to a file.
static async Task ReceiveFile(Socket socket, FileInfo file)
{
using (var fileStream = file.OpenWrite())
using (var networkStream = new NetworkStream(socket, false))
{
await networkStream.CopyToAsync(fileStream);
}
}
如果您需要报告进度,您可以使用缓冲区并报告复制的字节数:
static async Task SendFile(FileInfo file, Socket socket)
{
var readed = -1;
var buffer = new Byte[4096];
using (var networkStream = new BufferedStream(new NetworkStream(socket, false)))
using (var fileStream = file.OpenRead())
{
while(readed != 0)
{
readed = fileStream.Read(buffer, 0, buffer.Length);
networkStream.Write(buffer, 0, readed);
Console.WriteLine("Copied " + readed);
}
await networkStream.FlushAsync();
}
}
static async Task ReceiveFile(Socket socket, FileInfo file)
{
var readed = -1;
var buffer = new Byte[4096];
using (var fileStream = file.OpenWrite())
using (var networkStream = new NetworkStream(socket, false))
{
while (readed != 0)
{
readed = networkStream.Read(buffer, 0, buffer.Length);
fileStream.Write(buffer, 0, readed);
Console.WriteLine("Copied " + readed);
}
}
}