7

我用 Kinect 设备捕获了视频流。我需要通过网络发送这个流。为此,我使用了套接字。她是服务器和客户端中的一段代码:

private System.Drawing.Bitmap _CurrentBitmap;
    public ManWindow()
    {
        InitializeComponent();

        this.Loaded += delegate
        {
            BackgroundWorker bw1 = new BackgroundWorker();
            bw1.RunWorkerCompleted += (a, b) => bw1.RunWorkerAsync();
            bw1.DoWork += delegate { SendImage(); };
            bw1.RunWorkerAsync();
        };
    }
    public void SendImage()
    {
        Socket sListen = new Socket(AddressFamily.InterNetwork,
                                    SocketType.Stream,
                                    ProtocolType.Tcp);

        IPAddress IP = IPAddress.Parse("127.0.0.1");
        IPEndPoint IPE = new IPEndPoint(IP, 4321);

        sListen.Bind(IPE);
        sListen.Listen(2);

        while (true)
        {
            Socket clientSocket;
            clientSocket = sListen.Accept();

            var converter = new System.Drawing.ImageConverter();
            byte[] buffer = (byte[])converter.ConvertTo(_CurrentBitmap, typeof(byte[]));
            clientSocket.Send(buffer, buffer.Length, SocketFlags.None);
        }
    }

客户:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        BackgroundWorker bw11111 = new BackgroundWorker();
        bw11111.RunWorkerCompleted += (a, b) => bw11111.RunWorkerAsync();
        bw11111.DoWork += delegate { Recive(); };
        bw11111.RunWorkerAsync();
        Recive();
    }

    public void Recive()
    {
        Socket s = new Socket(AddressFamily.InterNetwork,
                            SocketType.Stream,
                            ProtocolType.Tcp);

        IPAddress IP = IPAddress.Parse("127.0.0.1");
        IPEndPoint IPE = new IPEndPoint(IP, 4321);
        s.Connect(IPE);

        while (true)
        {

            byte[] buffer = new byte[1000000];

            s.Receive(buffer, buffer.Length, SocketFlags.None);

            MemoryStream ms = new MemoryStream(buffer);

            ms.Write(buffer, 0, buffer.Length);
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(ms);

            Dispatcher.BeginInvoke(new Action(() =>
            {
                rgbImage11.Source = bitmap.ToBitmapSource();
            }));

        }
    }

_CurrentBitmap 是从 Kinect 读取的帧,每 1 秒更新一次。客户端启动时,调用Socket Receive方法,接收帧,转换为位图后分配给Image WPF控件。我的问题是这个动作发生在客户端并没有重复循环。

4

1 回答 1

3

我认为您做对了,尽管根据您的需要 UDP 套接字可能更有意义。尝试将您的服务器代码更改为以下内容:

while (true)
{
     Socket clientSocket;
     clientSocket = sListen.Accept();

     var converter = new System.Drawing.ImageConverter();
     while(true) // find a better way to determine that the picture is still updating?
    {
        byte[] buffer = (byte[])converter.ConvertTo(_CurrentBitmap, typeof(byte[]));
        clientSocket.Send(buffer, buffer.Length, SocketFlags.None);
    }
}

您正在向您的客户端发送一个位图,然后退出循环。套接字不会保持打开状态,因此您的客户端会运行一次它的循环。

于 2012-08-07T12:19:18.433 回答