发送端:
-
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();
-
}