我正在尝试创建服务器Windows窗体应用程序但我的代码在调用Listen方法时抛出0x80004005错误。 我做错了什么?
Private Sub StartUdpReceiveThread(ByVal Puerto As Integer)
If Not UdpOpen Then
Try
permission = New SocketPermission(NetworkAccess.Accept, TransportType.Udp, "", SocketPermission.AllPorts)
sListener = Nothing
permission.Demand()
'Dim ipHost As IPHostEntry = Dns.GetHostEntry("")
Dim ipAddr As IPAddress = IPAddress.Any
ipEndPoint = New IPEndPoint(ipAddr, CInt(Me.PuertoEscuchaLbl.Text))
'sListener = New Socket(ipAddr.AddressFamily, SocketType.Unknown, ProtocolType.Udp)
sListener = New Socket(ipAddr.AddressFamily, SocketType.Dgram, ProtocolType.UDP)
' Associates a Socket with a local endpoint
sListener.Bind(ipEndPoint)
sListener.Listen(5)
' Begins an asynchronous operation to accept an attempt
Dim aCallback As New AsyncCallback(AddressOf AcceptCallback)
sListener.BeginAccept(aCallback, sListener)
PrintLog("Server listening on " & ipEndPoint.Address.ToString & " port: " & ipEndPoint.Port)
UdpOpen = True
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End If
End Sub
编辑: CallBack方法 Public Sub AcceptCallback(作为IAsyncResult) Dim listener As Socket = Nothing
' A new Socket to handle remote host communication
Dim handler As Socket = Nothing
Try
' Receiving byte array
Dim buffer As Byte() = New Byte(1023) {}
' Get Listening Socket object
listener = DirectCast(ar.AsyncState, Socket)'<-- Here raises an error
' Create a new socket
handler = listener.EndAccept(ar)
handler.NoDelay = False
' Creates one object array for passing data
Dim obj As Object() = New Object(1) {}
obj(0) = buffer
obj(1) = handler
handler.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, New AsyncCallback(AddressOf ReceiveCallback), obj)
' Begins an asynchronous operation to accept an attempt
Dim aCallback As New AsyncCallback(AddressOf AcceptCallback)
listener.BeginAccept(aCallback, listener)
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub