setblocking(0) PROBLEM!

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!")

Hi,

I too have similar problem like you… im trying to connect external client program to that of the blender server program with UDP socket … so that it should get data from client and it should show the received data in blender output console… any one have idea, to how to do it… please it will be great if someone help in this…

Python sockets are blocking by default. What that means is that when you call socket.read() the function will not return until your data has been read or there is an error on the socket. i.e. The socket “blocks” execution until the operation has completed. Because your code gets blocked in the recv() call, your game freezes.

When you call “socket.setblocking(0)” on a socket, it puts the socket into non-blocking mode. If there is no data to receive, then an exception is raised instead of blocking your program.


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)

# NEW CODE to set non-blocking
UDPSock.setblocking(0)
UDPSock.bind(addr)

# Receive messages
try:
  data,addr = UDPSock.recvfrom(buf)

  if not data:
    print ("
FIN!")
    break
  else:
    print ("
'", data,"'")

except socket.error:
  # Normal operation, you probably won't have data most of the time.
  pass

# Close socket
UDPSock.close()
print ("
END!")

Things to watch out for.

  • I have not run or tested this code so there might be syntax or logic errors in it.
  • I would imagine that you would call this from an ‘Always’ sensor so you could check for new data once a frame. However, this code creates and closes the socket each time. If you did this then you would want to do some init code so that you only create the socket the first time the script was called. On subsequent calls, you just check to see if data is present. You would close the socket when your game exits.
  • I’m not sure if looping on ‘Always’ is the best approach for this in the BGE, I have not researched the topic. However, for simply UDP data, it would probably work ok.