C# Socket 大文件传输代码
时间: 2023-12-07 12:21:10 浏览: 84
以下是 C# 中使用 Socket 进行大文件传输的示例代码:
服务器端代码:
```csharp
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Program {
static void Main(string[] args) {
// 设置监听地址和端口号
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 8888);
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 开始监听
listenSocket.Bind(endPoint);
listenSocket.Listen(10);
Console.WriteLine("等待客户端连接...");
// 接收客户端连接请求
Socket clientSocket = listenSocket.Accept();
// 接收文件名
byte[] fileNameBytes = new byte[1024];
int recvLength = clientSocket.Receive(fileNameBytes);
string fileName = Encoding.UTF8.GetString(fileNameBytes, 0, recvLength);
Console.WriteLine("接收到文件名:" + fileName);
// 接收文件大小
byte[] fileSizeBytes = new byte[8];
recvLength = clientSocket.Receive(fileSizeBytes);
long fileSize = BitConverter.ToInt64(fileSizeBytes, 0);
Console.WriteLine("接收到文件大小:" + fileSize);
// 创建文件流并保存文件
using (FileStream fileStream = new FileStream(fileName, FileMode.Create)) {
byte[] buffer = new byte[1024];
long totalRecvLength = 0;
int recvCount;
while (totalRecvLength < fileSize) {
recvCount = clientSocket.Receive(buffer);
fileStream.Write(buffer, 0, recvCount);
totalRecvLength += recvCount;
}
}
Console.WriteLine("文件接收完成!");
// 终止连接
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
listenSocket.Close();
}
}
```
客户端代码:
```csharp
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Program {
static void Main(string[] args) {
// 连接服务器
IPAddress serverIP = IPAddress.Parse("127.0.0.1");
IPEndPoint endPoint = new IPEndPoint(serverIP, 8888);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(endPoint);
Console.WriteLine("连接服务器成功!");
// 发送文件名
string fileName = "test.txt";
byte[] fileNameBytes = Encoding.UTF8.GetBytes(fileName);
clientSocket.Send(fileNameBytes);
Console.WriteLine("发送文件名:" + fileName);
// 发送文件大小
FileInfo fileInfo = new FileInfo(fileName);
long fileSize = fileInfo.Length;
byte[] fileSizeBytes = BitConverter.GetBytes(fileSize);
clientSocket.Send(fileSizeBytes);
Console.WriteLine("发送文件大小:" + fileSize);
// 发送文件内容
using (FileStream fileStream = new FileStream(fileName, FileMode.Open)) {
byte[] buffer = new byte[1024 * 1024];
int sendCount;
while ((sendCount = fileStream.Read(buffer, 0, buffer.Length)) > 0) {
clientSocket.Send(buffer, sendCount, SocketFlags.None);
}
}
Console.WriteLine("文件发送完成!");
// 终止连接
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
```
注:以上代码只是一个简单的示例,实际应用中还需要进行异常处理、数据校验等操作。为了避免内存溢出,客户端和服务器端需要分段读取和发送文件内容。在示例代码中,客户端和服务器端每次读取和发送 1MB 的数据。如果需要传输的文件非常大,建议使用分块传输和多线程传输等优化方式。
阅读全文