冒着对TCPClient的新手,试图制作一个网络图象,向另一个将实施相同方案的IP发送小幅图像,每.4kb。 因此,它将同时派出和接收。
问题 我是在一次寄出之后的——tcpOut脱节,这意味着我只看到一个框架。 下面的法典有两节,首先,新FrameReceived在照相机的每张新形象上运行,然后发送,另一种方法是接收方法,将所接收的图像带入图像箱(在我自己从127.0.01时)。
private void fChat_Load(object sender, EventArgs e)
{
// fire up listener
listeningThread.RunWorkerAsync();
// tcp server setup
_tcpOut = new TcpClient();
_tcpOut.Connect("127.0.0.1", 54321);
}
private void NewFrameReceived(object sender, NewFrameEventArgs e)
{
Bitmap img = (Bitmap)e.Frame.Clone();
byte[] imgBytes = EncodeToJpeg(img, 25).ToArray();
if (_tcpOut.Connected) <-- PROBLEM HERE, THIS IS FALSE ON 2ND ITERATION
{
using (NetworkStream ns = _tcpOut.GetStream())
{
if (ns.CanWrite)
{
ns.Write(BitConverter.GetBytes(imgBytes.Length), 0, 4);
ns.Write(imgBytes, 0, imgBytes.Length);
}
}
}
}
private void listeningThread_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
// start listening for connections
_tcpIn = new TcpListener(IPAddress.Any, 54321);
_tcpIn.Start();
while (true)
{
using (TcpClient _inClient = _tcpIn.AcceptTcpClient()) // blocks until connected
{
using (NetworkStream stream = _inClient.GetStream())
{
Byte[] imgSizeBytes = new Byte[4];
stream.Read(imgSizeBytes, 0, 4);
int imgSize = BitConverter.ToInt32(imgSizeBytes, 0);
Byte[] imgBytes = new Byte[imgSize];
stream.Read(imgBytes, 0, imgSize);
MemoryStream ms = new MemoryStream(imgBytes);
Image img = Image.FromStream(ms);
picVideo.Image = img;
}
}
}
}
很多人预先表示感谢。