概述
发送端:
FileStream fs = new FileStream(@"7.jpg", FileMode.Open);
private void SendImage()
{
//实例化socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 56799);
socket.Connect(ipep);
long contentLength = fs.Length;
//第一次发送数据包的大小
socket.Send(BitConverter.GetBytes(contentLength));
while (true)
{
//每次发送128字节
byte[] bits = new byte[128];
int r = fs.Read(bits, 0, bits.Length);
if (r <= 0) break;
socket.Send(bits, r, SocketFlags.None);
}
socket.Close();
fs.Position = 0;
}
接收端:
private void RecviveImage()
{
new Thread(delegate ()
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 56799);
socket.Bind(ipep);
socket.Listen(2);
while (true)
{
try
{
byte[] data = new byte[8];
Socket clientSocket = socket.Accept();
if (clientSocket.Connected)
{
clientSocket.Receive(data, data.Length, SocketFlags.None);
long contentLength = BitConverter.ToInt64(data, 0);
int size = 0;
MemoryStream ms = new MemoryStream();
while (size < contentLength)
{
byte[] bits = new byte[128];
int r = clientSocket.Receive(bits, bits.Length, SocketFlags.None);
if (r <= 0) break;
ms.Write(bits, 0, r);
size += r;
}
Image img = Image.FromStream(ms);
this.Invoke((EventHandler) delegate
{
pictureBox1.Image = img; //更新在窗体控件上
});
clientSocket.Close();
ms.Flush();
ms.Close();
ms.Dispose();
}
}
catch { }
}
})
{ IsBackground = true }.Start();
}
最后
以上就是平淡短靴为你收集整理的C# Socket TCP发送图片与接收图片的全部内容,希望文章能够帮你解决C# Socket TCP发送图片与接收图片所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复