如何通过Tcplistener和TcpClient不间断连续接收实时图片
小弟最近在写一个远程桌面监控的程序,刚才发了一帖问解决了一个问题,可是程序还是不是不能正常运行但是不是同一个问题所以再开一帖
大体思路是 在服务端截取下桌面图片保存入 TCPListener创建的 NetWorkStream中 不断发送,两次间用标识符标识
在客户端 通过TcpClient的NetWorkStream读取字节数组先保存在一个临时的文件中 然后再加载到 picturebox中
可问题出来了。代码如下~
服务端:
TcpClient client;
NetworkStream stream;
private void Start()
{
TcpListener listener = new TcpListener(IPAddress.Any, Properties.Settings.Default.Port);
listener.Start();
client = listener.AcceptTcpClient();
stream = client.GetStream();
}
private void timer1_Tick(object sender, EventArgs e)
{
Bitmap bitmap = null;
bitmap = CutDesk(); //截取到图片
bitmap.Save(stream, ImageFormat.Jpeg); //直接保存到流中
byte[] flag = Encoding.ASCII.GetBytes("<FLAG>"); //写入分隔符
stream.Write(flag, 0, flag.Length);
}
客服端
public byte[] temp = null; //临时放部分字节数组
private void GetPictureBox()
{
if (File.Exists(Application.StartupPath + "\\temp.jpeg"))
File.Delete(Application.StartupPath + "\\temp.jpeg");
byte[] bs = new byte[4096];
int readSize = 0;
FileStream fs = File.OpenWrite(Application.StartupPath + "\\temp.jpeg");
while (true)
{
readSize = netstream.Read(bs, 0, 4096);
string str = new string(Encoding.ASCII.GetChars(bs));
string[] strs = str.Split(new string[] { " <FLAG>" },
StringSplitOptions.RemoveEmptyEntries);
if (strs.Length == 1)
{
if (temp != null)
{
fs.Write(temp, 0, temp.Length);
fs.Flush(); //通过刚才那贴解决了不能写入的问题
temp = null;
}
fs.Write(bs, 0, readSize); //可以成功写入
}
else
{
fs.Write(Encoding.ASCII.GetBytes(strs[0].ToCharArray()), 0, strs[0].Length);
temp = Encoding.ASCII.GetBytes(strs[1].ToCharArray());
fs.Close();
break;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
using (Stream filestream = File.OpenRead(Application.StartupPath + "\\temp.jpeg"))
{
pictureBox1.Image = Image.FromStream(filestream);
}
}
但是第二次接收到的图片发生错误不能正常打开,第一次接收到的图片是正常的,所以不知道该怎样写了
或者能够让pictureBox直接通过流读取…… 以上程序出来什么问题,或者还有其他的解决方案
还请达人帮忙解答~