TCP客户端断开连接

本文关键字:连接 断开 客户端 TCP | 更新日期: 2023-09-27 18:20:07

我是TCPClient的新手,我正试图制作一个网络摄像头应用程序,将每个约4kb的小图像发送到另一个IP,该IP将运行相同的程序。所以它将同时发送和接收。

我遇到的问题是_tcpOut在一次发送后断开连接,这意味着我只看到一帧。在下面的代码中,有两个部分,首先NewFrameReceived在相机的每个新图像上运行,然后发送,另一种方法是接收方法,它将接收到的图片放入图片框(目前我自己的图片来自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;
                }
            }
        }
    }

非常感谢。

TCP客户端断开连接

它会断开连接,因为您正在使用using语句处理TcpClient。