我是TCPClient的新手,我试图制作一个网络摄像头应用,该应用将每个〜4kb的小图像发送到另一个IP,该IP将运行相同的程序。因此它要同时发送和接收。
我遇到的问题是_tcpOut在发送一次后断开连接,这意味着我只能看到一帧。在下面的代码中,分为两个部分,首先在相机上的每个新图像上运行NewFrameReceived,然后将其发送,另一种方法是receive方法,将接收到的图片放入图片框(此刻我自己从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;
}
}
}
}
提前谢谢了。
最佳答案
由于您要使用using语句处置TcpClient,因此它会断开连接。
关于c# - TCP客户端断开连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8828330/