c# socket通信 传输文件
时间: 2024-11-29 09:39:15 浏览: 4
在C#中,使用Socket进行文件传输通常是通过分块读写的方式来实现的,因为一次完整的文件可能会非常大,不适合一次性发送。这里是一个简单的示例,展示如何使用TCP协议进行文件上传和下载:
### 文件上传:
1. **打开套接字并设置服务器端口**:
```csharp
TcpListener listener = new TcpListener(IPAddress.Any, PortNumber);
listener.Start();
```
2. **接受连接并处理文件发送**:
```csharp
Socket client = listener.AcceptSocket();
using (FileStream fileStream = File.OpenRead(FileToUpload))
{
byte[] buffer = new byte[BufferSize];
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
client.Send(buffer, bytesRead);
}
}
fileStream.Close();
client.Close();
```
### 文件下载:
1. **服务器创建套接字并监听客户端请求**:
```csharp
TcpClient client = await listener.AcceptTcpClientAsync();
```
2. **创建文件流准备接收文件**:
```csharp
NetworkStream networkStream = client.GetStream();
using (FileStream outputStream = File.Create(DownloadPath))
{
byte[] buffer = new byte[BufferSize];
int bytesReceived;
while ((bytesReceived = networkStream.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, bytesReceived);
}
}
networkStream.Close();
client.Close();
```
阅读全文