使用C#网络编程写一个服务端和客户端连接后可以互发图片的程序并给出代码
时间: 2024-03-21 17:40:34 浏览: 124
以下是一个简单的使用C#网络编程实现客户端和服务端互发图片的程序:
服务端代码:
```csharp
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Server
{
static void Main(string[] args)
{
TcpListener listener = new TcpListener(IPAddress.Any, 8080);
listener.Start();
Console.WriteLine("Server started, waiting for connections...");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Client connected from " + client.Client.RemoteEndPoint.ToString());
HandleClient(client);
}
listener.Stop();
}
static void HandleClient(TcpClient client)
{
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[4];
stream.Read(buffer, 0, buffer.Length);
int imageSize = BitConverter.ToInt32(buffer, 0);
Console.WriteLine("Receiving image of size " + imageSize + " bytes");
buffer = new byte[imageSize];
stream.Read(buffer, 0, buffer.Length);
MemoryStream ms = new MemoryStream(buffer);
Image image = Image.FromStream(ms);
image.Save("received_image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
Console.WriteLine("Image saved to received_image.jpg");
client.Close();
}
}
```
客户端代码:
```csharp
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Client
{
static void Main(string[] args)
{
TcpClient client = new TcpClient("localhost", 8080);
Console.WriteLine("Connected to server");
NetworkStream stream = client.GetStream();
Image image = Image.FromFile("test_image.jpg");
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] buffer = BitConverter.GetBytes((int)ms.Length);
stream.Write(buffer, 0, buffer.Length);
buffer = ms.ToArray();
stream.Write(buffer, 0, buffer.Length);
Console.WriteLine("Image sent");
client.Close();
}
}
```
注意:以上代码仅为示例,没有进行错误处理和完整性检查,实际应用中还需要进行相应的处理。
阅读全文