For the life of me I tried googling and have come up with much. I am trying to add a listen functionality to my socket class. I figured making it roughly the same way as I made the connect methods would be a good idea. Heres what I have.
Public Sub Listen()
Try
_Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
_Socket.Listen(1)
_Socket.BeginAccept(AddressOf ConnectionRequest, Nothing)
Catch ex As Exception
RaiseEvent SocketError(ex)
End Try
End Sub
Private Sub ConnectionRequest()
_Socket.Accept()
_Socket.BeginReceive(_Buffer, SocketFlags.None, AddressOf DataFromRemoteClient, Nothing)
End Sub
Private Sub DataFromRemoteClient()
_Socket.Receive(_Buffer)
RaiseEvent DataRecieved(_Buffer.ToString)
End Sub
Suggestions and related comments welcome.
I have gotten this to work. Changed my code alot in part to code i found at http://www.codeguru.com/Csharp/Csharp/cs_network/sockets/article.php/c7695/
Here is the update segment
Public Sub Listen()
Dim ipHostInfo = Dns.GetHostEntry(Dns.GetHostName)
Dim ipAddress = ipHostInfo.AddressList(0)
_localip = New IPEndPoint(ipAddress.Any, 6112)
'_Socket =
_Socket.Bind(_localip)
_Socket.Listen(100)
'_Socket.BeginAccept(AddressOf ConnectionRequest, _State)
_Socket.BeginAccept(New AsyncCallback(AddressOf ConnectionRequest), _Socket)
End Sub
Private Sub ConnectionRequest(ByVal AR As IAsyncResult)
_Socket = _Socket.EndAccept(AR)
RaiseEvent ConnectedUI("Client Connected!")
_Socket.BeginReceive(_Buffer, 0, _
_Buffer.Length, _
SocketFlags.None, _
AddressOf DataFromRemoteClient, _
_Socket)
End Sub
Private Sub DataFromRemoteClient(ByVal AR As IAsyncResult)
Dim IRx As Integer = _Socket.EndReceive(AR)
Dim data As System.Text.Decoder = System.Text.Encoding.UTF8.GetDecoder
Dim chars As Char() = New Char(IRx) {}
Dim d As System.Text.Decoder = System.Text.Encoding.UTF8.GetDecoder()
Dim charLen As Integer = d.GetChars(_Buffer, 0, IRx, chars, 0)
Dim szData As New String(chars)
If charLen = 0 Then RaiseEvent DisconnectedUI("Connection Lost")
RaiseEvent DataRecieved(szData)
' RaiseEvent DataRecieved(_Buffer.ToString)
End Sub
Trying to figure out how to catch when the client disconnects now, lol.
Usually Sockets raise a SocketException when they send data once they're disconnected -- as well as bytesRead from your Recv() will be zero.
Will look into that. thanks.
your thoughts did lead me to detecting the closing of the connection. unfortunate that until I fix my threading error this problem does me little good,lol.