C# TCP服务异步向客服端传输多个文件到客服端保存到本地
时间: 2024-09-29 13:09:52 浏览: 56
在C#中,通过TCP协议创建一个异步的文件传输服务,你可以使用`Socket`或`.NET Core`的`System.Net.Sockets`库。下面是一个简化的示例,展示了如何使用`TcpListener`监听客户端连接,并通过`FileStream`异步发送多个文件:
```csharp
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class FileServer
{
private TcpListener listener;
private int port = 8000; // 设置监听端口
public async Task Start()
{
listener = new TcpListener(IPAddress.Any, port);
await listener.StartAsync();
Console.WriteLine($"TCP server started on {listener.LocalEndpoint}");
while (true)
{
var client = await listener.AcceptTcpClientAsync();
Console.WriteLine($"Accepted connection from: {client.Client.RemoteEndPoint}");
await HandleFileTransfer(client);
}
}
private async Task HandleFileTransfer(TcpClient client)
{
try
{
using Stream inputStream = client.GetStream();
string[] filesToSend = { "file1.txt", "file2.jpg" }; // 文件列表
foreach (string file in filesToSend)
{
byte[] buffer = File.ReadAllBytes(file);
await SendFileStream(inputStream, buffer, file);
}
Console.WriteLine("Files sent successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
client.Close();
}
}
private async Task SendFileStream(Stream outputStream, byte[] data, string fileName)
{
using (MemoryStream memoryStream = new MemoryStream(data))
using (NetworkStream networkStream = new NetworkStream(outputStream))
{
ASCIIEncoding asciiEncoding = new ASCIIEncoding();
string filePathLength = asciiEncoding.GetString(BitConverter.GetBytes(data.Length));
await networkStream.WriteAsync(asciiEncoding.GetBytes(filePathLength), 0, filePathLength.Length);
await networkStream.WriteAsync(memoryStream.ToArray(), 0, data.Length);
}
}
// 主函数启动服务
static void Main(string[] args)
{
var server = new FileServer();
server.Start().GetAwaiter().GetResult();
}
}
```
在这个例子中,服务器首先接收来自客户端的连接,然后遍历文件列表并逐个读取每个文件的内容,将其转换为字节数组,再通过网络流异步发送给客户端。每个文件之前会先发送一个表示文件长度的信息。
阅读全文