新闻简介:
英文原文:http://www.devx.com/dotnet/Article/33637
译者Jack 五邑技术网
在我早期为DevX写的两篇文章中,"旧摄像头玩新把戏:在您的.NET程序中应用视频捕捉" 和 "用网络视频和伺服器构建一个强大的安防系统," 我已展示如何将你的网络摄像头与你的.NET程序线路合,并利用它来实现监视的目的. 然而,使用这些解决方案,只能在本地的电脑上看运行网络摄像头的图像. 这一次我们要实现一个有趣的扩大应用,使视频可以通过因特网远程观看.
然后在这篇文章里我将教你您怎么使用socket通信从服务器到远程客户发送一个在线视频图像。这篇文章中的样例包括:
- 服务器端播放从网络摄像头上视频捕获的图像
-
客户端从服务器接收直播图像
服务器将允许多个客户端同时连接到它。尤其,这是对您能使用它在您的办公室监测您的家或孩子的家庭环境的有用应用程序.
创造服务器端
首先我要创造服务器端。使用Visual Studio 2005,创造一种新Windows 应用程序并命名为RemoteMonitoring 。在默认的Form1中,增加PictureBox 控件(参见 图 1) 和设置它的属性如下:
- Size—449,253
- SizeMode—StretchImage
Imports System.Runtime.InteropServices
定义用于显示摄像头图像的常量和变量轮:
Public Class Form1 '---constants for capturing the video from webcam--- Const WM_CAP_START = &H400S Const WS_CHILD = &H40000000 Const WS_VISIBLE = &H10000000 Const WM_CAP_DRIVER_CONNECT = WM_CAP_START + 10 Const WM_CAP_DRIVER_DISCONNECT = WM_CAP_START + 11 Const WM_CAP_EDIT_COPY = WM_CAP_START + 30 Const WM_CAP_SEQUENCE = WM_CAP_START + 62 Const WM_CAP_FILE_SAVEAS = WM_CAP_START + 23 Const WM_CAP_SET_SCALE = WM_CAP_START + 53 Const WM_CAP_SET_PREVIEWRATE = WM_CAP_START + 52 Const WM_CAP_SET_PREVIEW = WM_CAP_START + 50 Const SWP_NOMOVE = &H2S Const SWP_NOSIZE = 1 Const SWP_NOZORDER = &H4S Const HWND_BOTTOM = 1 '---used as a window handle--- Dim hWnd As Integer
'--The capGetDriverDescription function retrieves the version ' description of the capture driver-- Declare Function capGetDriverDescriptionA Lib "avicap32.dll" _ (ByVal wDriverIndex As Short,_ ByVal lpszName As String,ByVal cbName As Integer,_ ByVal lpszVer As String,_ ByVal cbVer As Integer) As Boolean '--The capCreateCaptureWindow function creates a capture window-- Declare Function capCreateCaptureWindowA Lib "avicap32.dll" _ (ByVal lpszWindowName As String,ByVal dwStyle As Integer,_ ByVal x As Integer,ByVal y As Integer,_ ByVal nWidth As Integer,_ ByVal nHeight As Short,ByVal hWnd As Integer,_ ByVal nID As Integer) As Integer '--This function sends the specified message to a window or ' windows-- Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hwnd As Integer,ByVal Msg As Integer,_ ByVal wParam As Integer,_ <MarshalAs(UnmanagedType.AsAny)> ByVal lParam As Object) _ As Integer '--Sets the position of the window relative to the screen buffer-- Declare Function SetWindowPos Lib "user32" Alias "SetWindowPos" _ (ByVal hwnd As Integer,_ ByVal hWndInsertAfter As Integer,ByVal x As Integer,_ ByVal y As Integer,_ ByVal cx As Integer,ByVal cy As Integer,_ ByVal wFlags As Integer) As Integer '--This function destroys the specified window-- Declare Function DestroyWindow Lib "user32" _ (ByVal hndw As Integer) As Boolean
定义PreviewVideo()了程序,可以让你在PictureBox控件里播放捕捉于视频摄像头的图像:
'---preview the selected video source--- Private Sub PreviewVideo(ByVal pbCtrl As PictureBox) hWnd = capCreateCaptureWindowA(0,_ WS_VISIBLE Or WS_CHILD,_ 0,pbCtrl.Handle.ToInt32,0) If SendMessage( _ hWnd,WM_CAP_DRIVER_CONNECT,_ 0,0) Then '---set the preview scale--- SendMessage(hWnd,WM_CAP_SET_SCALE,True,0) '---set the preview rate (ms)--- SendMessage(hWnd,WM_CAP_SET_PREVIEWRATE,30,0) '---start previewing the image--- SendMessage(hWnd,WM_CAP_SET_PREVIEW,0) '---resize window to fit in PictureBox control--- SetWindowPos(hWnd,HWND_BOTTOM,_ pbCtrl.Width,pbCtrl.Height,_ SWP_NOMOVE Or SWP_NOZORDER) Else '--error connecting to video source--- DestroyWindow(hWnd) End If End Sub
Private Sub Form1_Load( _ ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles MyBase.Load PreviewVideo(PictureBox1) End Sub
第一步要认识到来自摄像头的视频可以保存为各自的图象. 在客户端显示一系列连续图象,类似观看视频流. 为了捕捉一个图像,我将定义下面的子程序:
这里,我先复制一个显示在PictureBox 控件里的图象到剪贴板里,然后把它转换成图形对象,并保存进一个内存流里,最后,我将内存流作为一系列的字节写出,这些字节被保存进一个全局变量Image里,这个变量定义在Module1.vb (右键点击项目名称,在解决方案资源管理器中选择添加|新项目的末尾. 然后选择 模块):保存图象作为字节序列阵让我更容易地通过socket联接传送图像
- Enabled—True
- Interval—100
双击在Timer定时器控件(位于在Form1 之下) 显示出它的Tick事件控件。编码Tick事件如下:
Figure 3. Communication between a client and the server involves a Send message that receives a video capture as a reply. |
Now,to enable this communication,add a new class to the project and name it WebCamClient.vb. Import the following namespace:
Figure 4. Populate Form1 with the varIoUs controls shown. |
- Size—449,253
- SizeMode—StretchImage
Switching to the code-behind of Form1,import the following namespace:
Imports System.Net.Sockets
Imports System.IO
Declare the following constant and member variables:
Public Class Form1
'---get own IP address---
Private ips As Net.IPHostEntry = _
Net.Dns.GetHostEntry(Net.Dns.GetHostName())
'---port nos and server IP address---
Const PORTNO As Integer = 500
Private server_IP As String = " 127.0.0.1"
'---size of the video image---
Const SIZEOFIMAGE As Integer = 341504
'---use for connecting to the server---
Private client As TcpClient
'--used for sending and receiving data---
Private data() As Byte
'---used for receiving images from the server---
Private t As System.Threading.Thread
Code the Click event handler of the Start button control as follows:
Private Sub btnStartStop_Click( _
ByVal sender As System.Object,_
ByVal e As System.EventArgs) _
Handles btnStartStop.Click
If CType(sender,Button).Text = "Start" Then
Try
'---set the server IP address---
server_IP = txtServerIP.Text
'---connect to the server---
client = New TcpClient
client.Connect(server_IP,PORTNO)
ReDim data(client.ReceiveBufferSize - 1)
'---send message---
SendMessage("Send")
'---begin reading data asynchronously from the
' server---
t = New System.Threading.Thread( _
AddressOf ReceiveImageLoop)
t.Start()
'---change the text on the Button---
CType(sender,Button).Text = "Stop"
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
Else
'---send message---
SendMessage("Stop")
t.Abort()
'---change the text on the Button---
CType(sender,Button).Text = "Start"
End If
End Sub
You first connect to the server using its IP address and port number. You then send a "Send" message to the server to indicate that you are ready to receive the image. You spin off a thread so that you can receive images (via the
ReceiveImageLoop() subroutine) asynchronously.
The ReceiveImageLoop() subroutine calls the ReceiveImage() function indefinitely,until an error occurs:
Private Sub ReceiveImageLoop()
'---keep on receiving image until an error occurs---
While ReceiveImage()
End While
'---display error message---
MsgBox("Server has stopped responding. Please try" & _
& " restarting the video.")
End Sub
The
ReceiveImage() function reads the incoming image data (in blocks of 8192 bytes,as defined by the ReceiveBufferSize property of the TcpClient class) sent from the server. As each image sent is 341504 bytes (defined by the SIZEOFIMAGE constant; this value is dependent on the web cam used),you will therefore read the number of bytes as expected. Once the image is received,display it in the PictureBox control. To receive the next image from the server,send another "Send" message:
'---receive video image from server---
Public Function ReceiveImage() As Boolean
Dim s As New MemoryStream
Try
Dim nws As NetworkStream = client.GetStream
Dim counter As Integer = 0
Dim totalBytes As Integer = 0
Do
'---read the incoming data---
Dim bytesRead As Integer = _
nws.Read(data,client.ReceiveBufferSize)
totalBytes += bytesRead
'---write the byte() array into the memory stream---
s.Write(data,bytesRead)
counter += 1
Loop Until totalBytes >= SIZEOFIMAGE
'---display the image in the PictureBox control---
PictureBox1.Image = Image.FromStream(s)
Catch ex As InvalidOperationException
'---ignore this error---
Console.WriteLine(ex.ToString)
Catch ex As Exception
Console.WriteLine(ex.ToString)
Return False
End Try
'---ask the server to send the next image---
SendMessage("Send")
Return True
End Function
The
SendMessage() subroutine sends a message to the server:
'---Sends a message to the server---
Private Sub SendMessage(ByVal message As String)
'---adds a carriage return char---
message += vbLf
Try
'---send the text---
Dim ns As System.Net.Sockets.NetworkStream
SyncLock client.GetStream
ns = client.GetStream
Dim bytesToSend As Byte() = _
System.Text.Encoding.ASCII.GetBytes(message)
'---sends the text---
ns.Write(bytesToSend,bytesToSend.Length)
End SyncLock
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
End Sub
When Form1 is closed,kill the thread that listens asynchronously for incoming image data:
Private Sub Form1_FormClosing( _
ByVal sender As Object,_
ByVal e As System.Windows.Forms.FormClosingEventArgs) _
Handles Me.FormClosing
t.Abort()
End Sub
Testing the Applications
You can test both the server and the client on one single machine. Simply set the IP_Address variable (on the server) to "127.0.0.1" and then press F5 in Visual Studio 2005 to test the application. For the client,type the server IP address (which is 127.0.0.1) and click the Start button. You should see the same image on both the client and the server (see Figure 5).
Figure 5. You can test the client and the server on the same machine. |
Some Points to Note
Please note the following points when testing the client and the server:
- The server application needs to be visible on screen. If it is minimized,the client will not be able to receive the image captured by the web cam. This is due to the fact that the application is capturing whatever images are shown on the screen.
- For simplicity I have not added any security features into the server. In reality,you can add credentials information to the message sent to the server before the server sends the video image over to the client.