我是TCPClient的新手,我试图制作一个网络摄像头应用程序,将每个~4kb的小图像发送到另一个运行相同程序的IP。所以它会在同一时间发送和接收。
我遇到的问题是_tcpOut在一次发送后断开连接,这意味着我只看到一帧。在下面的代码中有两个部分,首先是NewFrameReceived运行在来自摄像机的每个新图像上,然后发送,另一个方法是接收方法,它将接收到的pic放入一个图片框(此时我自己的127.0.0.1):
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;
}
}
}
}
非常感谢提前。