TCP实现图片上传与读取

发送端:


 
 
  1. FileStream fs = new FileStream( @"7.jpg", FileMode.Open);
  2. private void SendImage()
  3. {
  4. //实例化socket
  5. Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  6. IPEndPoint ipep = new IPEndPoint(IPAddress.Parse( "127.0.0.1"), 56799);
  7. socket.Connect(ipep);
  8. long contentLength = fs.Length;
  9. //第一次发送数据包的大小
  10. socket.Send(BitConverter.GetBytes(contentLength));
  11. while ( true)
  12. {
  13. //每次发送128字节
  14. byte[] bits = new byte[ 128];
  15. int r = fs.Read(bits, 0, bits.Length);
  16. if (r <= 0) break;
  17. socket.Send(bits, r, SocketFlags.None);
  18. }
  19. socket.Close();
  20. fs.Position = 0;
  21. }

 

接收端:


 
 
  1. private void RecviveImage()
  2. {
  3. new Thread( delegate ()
  4. {
  5. Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  6. IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 56799);
  7. socket.Bind(ipep);
  8. socket.Listen( 2);
  9. while ( true)
  10. {
  11. try
  12. {
  13. byte[] data = new byte[ 8];
  14. Socket clientSocket = socket.Accept();
  15. if (clientSocket.Connected)
  16. {
  17. clientSocket.Receive(data, data.Length, SocketFlags.None);
  18. long contentLength = BitConverter.ToInt64(data, 0);
  19. int size = 0;
  20. MemoryStream ms = new MemoryStream();
  21. while (size < contentLength)
  22. {
  23. byte[] bits = new byte[ 128];
  24. int r = clientSocket.Receive(bits, bits.Length, SocketFlags.None);
  25. if (r <= 0) break;
  26. ms.Write(bits, 0, r);
  27. size += r;
  28. }
  29. Image img = Image.FromStream(ms);
  30. this.Invoke((EventHandler) delegate
  31. {
  32. pictureBox1.Image = img; //更新在窗体控件上
  33. });
  34. clientSocket.Close();
  35. ms.Flush();
  36. ms.Close();
  37. ms.Dispose();
  38. }
  39. }
  40. catch { }
  41. }
  42. })
  43. { IsBackground = true }.Start();
  44. }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值