UDP客户端缓冲区太小

时间:2014-06-25 14:20:26

标签: vb.net sockets udp udpclient

大家好,我正在开发一个需要通过UDP套接字发送图像的应用程序。我知道TCP是一个更好的协议,但是在Java中使用Kryonet我已经知道UDP对于这种类型的应用程序更好。我有这个小课程:

Imports System.Net.Sockets
Imports System.Net
Imports System.Text.Encoding

Public Class BasicUDPClient
    Event ClientMessageReceived(ByVal msg() As Byte)

    Public Property HostName As String = "localhost"
    Public Property Port As Integer = 8991

    Dim sender As New UdpClient(0)
    Dim receiver As New UdpClient(Port)
    Dim th_recv As New Threading.Thread(AddressOf Receive)
    Dim run As Boolean
    Dim ep As New IPEndPoint(System.Net.IPAddress.Any, 0)
    Public Sub New(ByVal host As String, ByVal port As Integer)
        HostName = host
        Me.Port = port
        receiver.Client.Blocking = False
        '10485760 = 10MB
        receiver.Client.ReceiveBufferSize = 10485760
        sender.Client.SendBufferSize = 10485760
        receiver.Client.ReceiveTimeout = 5000
        StartReceive()
    End Sub

    Public Sub SendString(ByVal msg As String)
        SendMessage(UTF8.GetBytes(msg))
    End Sub

    Public Sub SendMessage(ByVal msg() As Byte)
        sender.Connect(HostName, Port)
        sender.Send(msg, msg.Length)
    End Sub

    Public Sub StartReceive()
        run = True
        th_recv = New Threading.Thread(AddressOf Receive)
        th_recv.Start()
    End Sub

    Public Sub StopReceive()
        run = False
    End Sub

    Private Sub Receive()
        While (run)
            Try
                RaiseEvent ClientMessageReceived(receiver.Receive(ep))
            Catch ex As Exception
                Debug.WriteLine("Error: " & ex.Message)
            End Try

        End While
    End Sub

End Class

它很好用字符串喜欢你好,但当我发送图像,大约200000-150000字节我得到一个错误说缓冲区低于数据包的内容(我可以发布错误消息的图像,但我的.net语言是西班牙语)

由于

1 个答案:

答案 0 :(得分:1)

  1. 使用UDP,您无法发送大于64KB的邮件。使用TCP,或者将自己的有效负载拆分成多条消息,这些消息非常复杂,因为消息可能会丢失。
  2. ReceiveBufferSize不是你想象的那样。使用它几乎没有帮助。
  3. 发送方和接收方的代码丢失,但sender.Connect看起来很奇怪,因为UDP是无连接的。