|
服务端发送图片
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.IO;
namespace 发图片
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket FuWuSocket;
Socket KeHuSocket;
Byte[] photo;
private void Form1_Load(object sender, EventArgs e)
{
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 6050);
FuWuSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
FuWuSocket.Bind(ipe);
FuWuSocket.Listen(10);
KeHuSocket = FuWuSocket.Accept();
Form1 from = new Form1();
from.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
Thread thread1=new Thread(new ThreadStart(fasong));
thread1.Start();
}
private void fasong()
{
for (int i = 0; i <5;i++ )
{
Image img = new Bitmap(@"D:\tupian\" + i.ToString() + ".jpg");
System.IO.MemoryStream mem = new MemoryStream(); //内存流
img.Save(mem, ImageFormat.Bmp); //将图片保存到指定的流
BinaryReader br = new BinaryReader(mem);
photo = mem.ToArray();
mem.Close();
KeHuSocket.Send(photo);
if(i==4)
{
i = 0;
}
Thread.Sleep(50);
}
}
}
}
客户端接收图片
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.IO;
namespace 接图片
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket KeHuSocket;
Byte[] byte1;
private void Form1_Load(object sender, EventArgs e)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
IPEndPoint ipe = new IPEndPoint(ip,6050);
KeHuSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
KeHuSocket.Connect(ipe);
if (KeHuSocket.Connected)
{
MessageBox.Show("连接成功");
ThreadStart ts = new ThreadStart(jieshou);
Thread thread1 = new Thread(ts);
thread1.Start();
}
}
private void button1_Click(object sender, EventArgs e)
{
}
private void jieshou()
{
while (true)
{
byte1 = new Byte[5000000];
KeHuSocket.Receive(byte1);
Byte[] photo = byte1;
if (photo!=null)
{
System.IO.MemoryStream mem = new MemoryStream(photo);
mem.Position=100;
Image img = Image.FromStream(mem);
mem.Close();
pictureBox1.Image = img;
Thread.Sleep(50);
}
}
}
}
}
当客户端图片接收多少后, Image img = Image.FromStream(mem); 提示mem参数无效
|
|