如果传送的图片是readonly,可以通过FileInfo.IsReadOnly = false先屏蔽readonly,不然本文代码会出现小错误:
Client Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
class Program
{
static void Main(string[] args)
{
SendImageToServer("image.jpg");
}
static void SendImageToServer(string imgURl)
{
if (!File.Exists(imgURl)) return;
FileStream fs = File.Open(imgURl, FileMode.Open);
byte[] fileBytes = new byte[fs.Length];
using (fs)
{
fs.Read(fileBytes, 0, fileBytes.Length);
fs.Close();
}
IPAddress address = IPAddress.Parse("127.0.0.1");
TcpClient client = new TcpClient();
client.Connect(address, 8000);
using (client)
{
NetworkStream ns = client.GetStream();
using (ns)
{
ns.Write(fileBytes, 0, fileBytes.Length);
}
}
}
}
Server code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
class Program
{
static TcpClient client;
static FileStream fs = new FileStream("image.jpg", FileMode.Create);
static int bufferlength = 200;
static byte[] buffer = new byte[bufferlength];
static NetworkStream ns;
static void Main(string[] args)
{
ConnectAndListen();
}
static void ConnectAndListen()
{
TcpListener listener = new TcpListener(IPAddress.Any, 8000);
listener.Start();
while (true)
{
Console.WriteLine("wait for connecting...");
client = listener.AcceptTcpClient();
Console.WriteLine("connected");
ns = client.GetStream();
if (ns.DataAvailable)
{
ns.BeginRead(buffer, 0, bufferlength, ReadAsyncCallBack, null);
}
}
}
static void ReadAsyncCallBack(IAsyncResult result)
{
int readCount;
readCount = client.GetStream().EndRead(result);
if (readCount < 1)
{
client.Close();
ns.Dispose();
fs.Dispose();
return;
}
fs.Write(buffer, 0, readCount);
ns.BeginRead(buffer, 0, 200, ReadAsyncCallBack, null);
}
}
该博客展示了如何使用C#进行图片的TCP传输。客户端通过读取本地图片文件并将其转换为字节数组,然后连接到服务器并发送。服务器端接收数据,将接收到的字节流写入文件,实现图片的接收。注意处理readonly属性以避免错误。
1万+

被折叠的 条评论
为什么被折叠?



