通过套接字进行屏幕共享

时间:2017-02-10 22:55:08

标签: vb.net sockets tcp screenshot networkstream

我正在使用套接字在VB.NET中创建我的第一个屏幕共享应用程序来建立连接。

这是客户端从服务器接收屏幕图像(它们都在线程中运行):

Private Sub startscreen()
    Using imgstream As NetworkStream = imgclient.GetStream()
        Using ms As New MemoryStream
            Dim read As Double
            Do
                If (imgstream.DataAvailable) Then
                    read = 0
                    ms.Seek(0, SeekOrigin.Begin)

                    While imgclient.Available
                        Dim buffer(imgclient.Available - 1) As Byte
                        imgstream.Read(buffer, 0, buffer.Length)
                        ms.Write(buffer, 0, buffer.Length)
                        read += buffer.Length
                    End While

                    Me.Text = "Frame bytes read: " & read
                    PictureBox1.Image = Image.FromStream(ms)
                    ms.Flush()
                 End If
                 Thread.Sleep(34) 'about 30 FPS
             Loop
        End Using
    End Using
End Sub

这是服务器端:

Private Sub screen()
    Using imgstream As NetworkStream = imgclient.GetStream()
        Using ms As New MemoryStream
            Do
                Thread.Sleep(34) 'about 30 FPS
                ms.Seek(0, SeekOrigin.Begin)
                Using img = ScreenCap()
                    img.Save(ms, Imaging.ImageFormat.Jpeg)
                End Using
                ms.WriteTo(imgstream)
            Loop
        End Using
    End Using
End Sub

Public Function ScreenCap() As Image
    Dim screenSize As Size = New Size(My.Computer.Screen.Bounds.Width, My.Computer.Screen.Bounds.Height)
    Dim screenGrab As New Bitmap(My.Computer.Screen.Bounds.Width, My.Computer.Screen.Bounds.Height) ', Imaging.PixelFormat.Format16bppRgb555)
    Dim g As Graphics = Graphics.FromImage(screenGrab)
    g.CopyFromScreen(New Point(0, 0), New Point(0, 0), screenSize)
    g.Dispose()
    Return screenGrab
End Function

主要问题是当我调用" Image.FromStream(ms)"函数,它有时是有效的,而其他函数则不依赖于我设置线程等待的毫秒数。在我的局域网中的两台不同的计算机上测试,大约1秒钟似乎没问题但总是具有高CPU网络使用率。如果我设置,例如说大约34毫秒来获得更多" LIVE",该函数因MemoryStream而抛出异常。我怎样才能加快速度?我现在有什么更聪明的方法吗?我还尝试在MemoryStream和/或MemoryStream上放置一个分隔符字节(如char =" *"),然后将其发送到一次读取一个字节的客户端,直到找到一个char等于分隔符。但事实证明这是一个糟糕的解决方案,因为如果转换为char,图像的单个字节可以表示分隔符。我的另一个问题是:如何更改图像质量和颜色深度?使用评论所说的是一个好方法:" Imaging.PixelFormat.Format16bppRgb555"

谢谢!

0 个答案:

没有答案