Socket freeze my game engine! please Help!

Hello!, please help:

I’m working with Blender 2.6 and python 3.1. I’m starting to work with udp sockets and wrote this server (but freeze the game engine. I read about setblocking(0), but I try it and havent found the way):

from socket import *

Set the socket parameters

host = “localhost”
port = 8882
buf = 1024
addr = (host,port)

Create socket and bind to address

UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

cont = 0

Receive messages

while (cont < 3):
cont = cont + 1
data,addr = UDPSock.recvfrom(buf)
if not data:
print ("
FIN!")
break
else:
print ("
‘", data,"’")

Close socket

UDPSock.close()
print ("
END!")

All newly created sockets start in blocking mode by default. This means that whenever you make a call to a function like recv(), recvfrom(), or accept(), the function blocks (does not return) until it receives some data from a sender. Since the BGE waits for all logic to complete before moving to the next game frame, your game will “freeze” if you try to receive data on a socket when nothing has been sent to it.

The solution, as you’ve probably deduce, is to set your socket to non-blocking mode.

UDPSock.setblocking(0)

Note that if you call recvfrom() on a non-blocking socket when there is no data to receive, it will raise an error (Errno 10035 on Windows). You should use a try-except clause to catch and handle this.

Mobious, thanks a lot, but
How exactly should I use the try-except clause that you mention??!!
Thanks again!

Something like this:

try:
    data, addr = UDPSock.recvfrom(buf)
except socket.error as sockErr:
     if sockErr.errno == 10035:
          return # do whatever you want when you don't received data
    else:
          raise sockErr # some other error has occured, you can handled it if you want to
# otherwised you've received some data successfully