C# Socket 文件传输代码
时间: 2023-07-12 17:37:54 浏览: 152
以下是 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];
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();
}
}
```
注:以上代码只是一个简单的示例,实际应用中还需要进行异常处理、数据校验等操作。
阅读全文