BGE - Keeping Socket Server open

Hi, I’ve been reading for about two days now, but am finally posting, I just cant seem to crack this nut myself.

Essentially, I have code that sends the current rotation value of 6 cubes to a TCP server

Here is the ‘sending’ bit of the code

import socket


host = "192.168.0.10"
port = 999

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))



def sendCI(command):
    s.send(str(command).encode('utf-8'))


sendCI("m1="+FL)
sendCI("m2="+ML)
sendCI("m3="+BL)


sendCI("m4="+FR)
sendCI("m5="+MR)
sendCI("m6="+BR)

s.close()

This works. It sends all 6 values across very quick to the TCP port.
However, the TCP server I am using seems to have a delay when it gets closed and re-opens. So While this works fine for the first frame, it causes a massive slow-down when the game is actually running. (about 1fps)

Is there a way, to open the TCP server in blender, and THEN simply send commands as the game is running?

EG: in one thread, connect to the TCP server, keep that open, and then in another script / thread, send the commands?

Thanks
Calumk

Yes, on your Python Controller logic brick, you need to run your script in ‘module’ mode instead of ‘script’ mode. Then you can change your code like so:


import socket


host = "192.168.0.10"
port = 999

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))



def sendCI(command):
    s.send(str(command).encode('utf-8'))

def controllerEntry(controller):
    sendCI("m1="+FL)
    sendCI("m2="+ML)
    sendCI("m3="+BL)


    sendCI("m4="+FR)
    sendCI("m5="+MR)
    sendCI("m6="+BR)

#s.close()

On the Python Controller logic brick, you want to point your script to ‘<your .py file w/o the .py>.controllerEntry’. That will open the connection to the server once and each frame just send the 6 commands.

Note, that I commented out the call to close the server.

There is a lot of error handling that you could add to this code to make it more robust, but this should get you going.