c# tcp传输文件代码
时间: 2023-12-07 09:05:22 浏览: 95
TCP文件传输代码
4星 · 用户满意度95%
以下是一个用C#实现的TCP传输文件的示例代码:
服务端:
```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, 1234);
listener.Start();
Console.WriteLine("等待客户端连接...");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("客户端已连接");
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
// 读取文件名
int byteCount = stream.Read(buffer, 0, buffer.Length);
string fileName = Encoding.UTF8.GetString(buffer, 0, byteCount);
// 读取文件内容
using (FileStream fileStream = File.Create(fileName))
{
while ((byteCount = stream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, byteCount);
}
}
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("127.0.0.1"), 1234);
NetworkStream stream = client.GetStream();
// 发送文件名
string fileName = "test.txt";
byte[] buffer = Encoding.UTF8.GetBytes(fileName);
stream.Write(buffer, 0, buffer.Length);
// 发送文件内容
using (FileStream fileStream = File.OpenRead(fileName))
{
while (fileStream.Position < fileStream.Length)
{
int byteCount = fileStream.Read(buffer, 0, buffer.Length);
stream.Write(buffer, 0, byteCount);
}
}
Console.WriteLine("文件传输完成");
client.Close();
}
}
```
需要注意的是,以上示例代码没有添加任何异常处理,实际使用中需要根据实际情况进行添加。
阅读全文