Created
April 2, 2016 14:59
-
-
Save MatteoRagni/91e0216c84d39aa0575fc25001759051 to your computer and use it in GitHub Desktop.
This is a simple Python module for Blender - Game network communication. This allow UDP connections in which `json` object are sent.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Server | |
# To use it: | |
# - Load this script in Blender Note editor as `net.py` | |
# - Select the objects that should handle the network logic (for example an empty or the camera) | |
# - Add an Always sensor with only raise up | |
# - Add a python controller as a module, that calls `net.serve` | |
# - connect sensor and controller | |
# - enjoy | |
import bge | |
import socket | |
import json | |
### Helpers ### | |
## Parser method | |
def _parser(js): | |
print("the variable js contains an object") | |
# In this function it is possible to parse | |
# tha object and execute something. | |
return | |
################################# | |
# Network class | |
class Server: | |
def __init__(self, host='localhost', port=9999): | |
self.addr = (host, port) | |
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
self.socket.setblocking(False) | |
self.socket.bind(self.addr) | |
def handle(self, addr, data): | |
print("=" * 20) | |
print("from %s: %s" % (addr,data)) | |
response = self.parser(data) | |
print("Response:") | |
print(response) | |
#resp_text = json.dumps(response) | |
#self.socket.sendto(resp_text.encode(), addr) | |
return | |
def receive(self): | |
while True: | |
try: | |
data, addr = self.socket.recvfrom(1024) | |
self.handle(addr, data.decode()) | |
except socket.error: | |
break | |
def parser(self, data): | |
try: | |
_json = json.loads(data) | |
except json.decoder.JSONDecodeError: | |
print("JSON data not valid") | |
return None | |
return _parser(_json) | |
##################################### | |
# Actually executed commands every frame | |
server = Server() | |
# server = Server('www.google.com', 80) | |
# Module function for Game Logic | |
def serve(): | |
server.receive() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment