Re: Need Help with this Async code
From: Tom Shelton (tshelton_at_YOUKNOWTHEDRILLcomcast.net)
Date: 01/31/05
- Next message: Bob: "Re: Crystal Reports - Setting up a one-to-many relationship in a crystal report"
- Previous message: Bob: "Re: Early binding arrays, best technique"
- In reply to: Terry Olsen: "Need Help with this Async code"
- Messages sorted by: [ date ] [ thread ]
Date: Sun, 30 Jan 2005 23:10:58 -0800
On 2005-01-30, Terry Olsen <tolsen64@hotmail.com> wrote:
> I'm trying to use Async Socket calls to create a tcp server. It goes into
> the listening correctly, but when I connect, it crashes with the following
> exception:
>
> An unhandled exception of type 'System.InvalidOperationException' occurred
> in system.dll
> Additional information: AcceptCallback
> There is no source code available for the current location.
>
> Here's the code. Hopefully someone can help me out.
> -----------------------------------------------------------
> Private sck As Socket 'Class level
>
> Private Sub btnStart_Click(ByVal sender As System.Object, _
> ByVal e As System.EventArgs) Handles btnStart.Click
> Dim addr As IPAddress = IPAddress.Parse("0.0.0.0")
> Dim ep As New IPEndPoint(addr, CInt(txtPort.Text))
> Dim sck As New Socket(AddressFamily.InterNetwork, _
> SocketType.Stream, ProtocolType.Tcp)
> sck.Bind(ep)
> sck.Listen(2)
> sck.BeginAccept(AddressOf AcceptCallback, Nothing)
> lblStatus.Text = "Listening"
> End Sub
>
> Private Sub AcceptCallback(ByVal ar As IAsyncResult)
> sck.EndAccept(ar) 'I believe this is my problem
> Dim bytes(4095) As Byte
> sck.BeginReceive(bytes, 0, bytes.Length, SocketFlags.None, _
> AddressOf ReceiveCallback, bytes)
> End Sub
>
> Private Sub ReceiveCallback(ByVal ar As IAsyncResult)
> Dim bytes() As Byte = CType(ar.AsyncState, Byte())
> Dim numbytes As Int32 = sck.EndReceive(ar)
> If numbytes = 0 Then
> Else
> End If
> End Sub
>
>
Terry...
Your trying to read off your server socket. When a socket connection is
accepted, the client is actually connected on a new socket so that the
server socket goes back to listening.
You should really be doing something like:
Private Sub AcceptCallback (ByVal ar As IAsyncResult)
Dim clt As Socket = sck.EndAccept(ar)
...
clt.BeginRecieve (....)
sck.BeginAccept (...)
End Sub
You might try looking through the async socket examples here:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconsockets.asp
HTH
-- Tom Shelton [MVP]
- Next message: Bob: "Re: Crystal Reports - Setting up a one-to-many relationship in a crystal report"
- Previous message: Bob: "Re: Early binding arrays, best technique"
- In reply to: Terry Olsen: "Need Help with this Async code"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|