I'm trying to create a server Windows Form application but my code throw a 0x80004005 error when call the Listen method. What I'm doing wrong?
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
Edit: CallBack method Public Sub AcceptCallback(ar As 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
Don't just pick the first IP address in IPHostEntry.AddressList
but search the array for an IPv4 address. See the example on this MSDN page .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.