c# 局域网文件传输
时间: 2023-11-08 17:05:12 浏览: 186
您可以使用 C# 的 Socket 编程实现局域网文件传输。具体步骤如下:
1. 创建一个服务器端和一个客户端,分别监听和连接指定的 IP 地址和端口号。
2. 服务器端接收客户端发送的文件,并将其保存到指定的路径下。
3. 客户端读取本地文件,并将其发送给服务器端。
以下是一个简单的示例代码:
服务器端:
```csharp
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Server
{
static void Main(string[] args)
{
// 创建一个监听器
TcpListener listener = new TcpListener(IPAddress.Any, 12345);
listener.Start();
Console.WriteLine("等待客户端连接...");
// 接受客户端连接
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("客户端已连接");
// 接收文件名和文件大小
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string fileName = Encoding.UTF8.GetString(buffer, 0, bytesRead);
bytesRead = stream.Read(buffer, 0, buffer.Length);
long fileSize = BitConverter.ToInt64(buffer, 0);
// 创建文件流并保存文件
using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
{
long totalBytesRead = 0;
while (totalBytesRead < fileSize)
{
int bytesToRead = (int)Math.Min(buffer.Length, fileSize - totalBytesRead);
bytesRead = stream.Read(buffer, 0, bytesToRead);
fileStream.Write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
}
}
Console.WriteLine("文件已保存");
// 关闭连接
client.Close();
listener.Stop();
}
}
```
客户端:
```csharp
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Client
{
static void Main(string[] args)
{
// 连接服务器
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("192.168.1.100"), 12345);
// 发送文件名和文件大小
NetworkStream stream = client.GetStream();
string fileName = "test.txt"; byte[] fileNameBytes = Encoding.UTF8.GetBytes(fileName);
stream.Write(fileNameBytes, 0, fileNameBytes.Length);
long fileSize = new FileInfo(fileName).Length;
byte[] fileSizeBytes = BitConverter.GetBytes(fileSize);
stream.Write(fileSizeBytes, 0, fileSizeBytes.Length);
// 发送文件内容
using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, bytesRead);
}
}
Console.WriteLine("文件已发送");
// 关闭连接
client.Close();
}
}
```
阅读全文