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
# Receive messages
data,addr = UDPSock.recvfrom(buf)
if not data:
# Normal operation, you probably won't have data most of the time.
# Close socket
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.