C# Socket 简易的图片传输
时间: 2023-07-12 15:33:16 浏览: 120
以下是一个简单的 C# Socket 图片传输的示例代码:
服务器端:
```csharp
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Program
{
static void Main(string[] args)
{
// 创建一个监听 Socket
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8888));
serverSocket.Listen(10);
Console.WriteLine("等待客户端连接...");
// 接收客户端连接
Socket clientSocket = serverSocket.Accept();
Console.WriteLine("客户端已连接");
// 接收图片数据
byte[] buffer = new byte[1024];
int count = clientSocket.Receive(buffer);
MemoryStream ms = new MemoryStream();
ms.Write(buffer, 0, count);
// 持续接收图片数据,直到接收完毕
while (count == buffer.Length)
{
count = clientSocket.Receive(buffer);
ms.Write(buffer, 0, count);
}
Console.WriteLine("图片接收完毕,共接收 " + ms.Length + " 字节数据");
// 保存图片到本地磁盘
FileStream fs = new FileStream("test.jpg", FileMode.Create);
ms.WriteTo(fs);
Console.WriteLine("图片保存成功");
// 关闭 Socket 和文件流
clientSocket.Close();
fs.Close();
Console.ReadKey();
}
}
```
客户端:
```csharp
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Program
{
static void Main(string[] args)
{
// 创建一个连接 Socket
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));
Console.WriteLine("连接服务器成功");
// 读取图片数据
FileStream fs = new FileStream("test.jpg", FileMode.Open);
byte[] buffer = new byte[1024];
int count = fs.Read(buffer, 0, buffer.Length);
// 发送图片数据
while (count > 0)
{
clientSocket.Send(buffer, 0, count, SocketFlags.None);
count = fs.Read(buffer, 0, buffer.Length);
}
Console.WriteLine("图片发送完毕,共发送 " + fs.Length + " 字节数据");
// 关闭 Socket 和文件流
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
fs.Close();
Console.ReadKey();
}
}
```
注意:这只是一个简单的示例,实际应用中需要考虑异常处理、数据分片、数据加密等问题。
阅读全文