我用 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控件。我的问题是这个动作发生在客户端并没有重复循环。