Socket works fine first time, fails second time

G

Guest

Hello all

I'm using a bit of very simple code to query a game server using a UDP
packet. It works the fine time I run it but then when I run it again straight
away it fails with..

"A message sent on a datagram socket was larger than the internal message
buffer or some other network limit, or the buffer used to receive a datagram
into was smaller than the datagram itself"

I reckon it's because the socket is not closing properly so is dtill open
when I run it a second time. I assume this is down to lingeroption but I
can't seem to set this to false as the syntax on msdn doesn't seem to work.
Could someeone give me a hand with this please? My code is below...

'SERVER QUERY
Dim A2S_SERVERQUERY_GETCHALLENGE() As Byte = {&HFF, &HFF, &HFF,
&HFF, &H57}

'DECLARE ENDPOINTS
Dim localIPEndPoint As IPEndPoint = New IPEndPoint(0, 0)
Dim remoteIPEndPoint As IPEndPoint = New
IPEndPoint(IPAddress.Parse("192.168.0.6"), 27015)
Dim remoteEndPoint As EndPoint = CType(remoteIPEndPoint, EndPoint)

Dim s As Socket = New Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp)

'BIND TO LOCAL PORT
s.Bind(localIPEndPoint)

'SET SOCKET TIMEOUT TO 1 SECOND
s.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, 1000)

'SEND QUERY STRING
s.SendTo(A2S_SERVERQUERY_GETCHALLENGE, remoteEndPoint)

Dim return_bytes(s.Available) As Byte
s.Receive(return_bytes, 0, s.Available, 0)

'CLOSE SOCKET
s.Close()
 
V

Vadym Stetsyak

Hello, Ben!

BH> 'SEND QUERY STRING
BH> s.SendTo(A2S_SERVERQUERY_GETCHALLENGE, remoteEndPoint)

BH> Dim return_bytes(s.Available) As Byte
BH> s.Receive(return_bytes, 0, s.Available, 0)

the problem here is that s.Available may return 0 and in few milliseconds ( when data arrive to the host ), it can show available data.
Either you have to check s.Available if it is 0, or introduce blocking Receive/ReceiveFrom call with fixed buffer size.

Receive/ReceiveFrom will be in the loop untill all the data is received.

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
 
G

Guest

Vadym

Thanks for taking the time to reply. Aah yes, you're right, I completely
missed that. I think it didn't occur to me as it always works fine the first
time so I thought that the code was fine in itself but it appears that this
is not the case.

Thanks again
Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top