我使用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秒更新一次。当Client启动时,调用Socket Receive方法,它接收帧并在转换为位图后将其指向Image WPF控件。我的问题是这个动作发生了,并且客户端循环不重复。
答案 0 :(得分: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);
}
}
您向客户端发送了一个位图,然后退出了循环。 套接字不会保持打开状态,因此客户端会循环运行一次。