Server TCP Python

Scripting in Blender with Python, and working on the API

Moderators: jesterKing, stiv

Post Reply
Tamaya
Posts: 0
Joined: Sat Nov 22, 2008 3:38 pm
Location: Toulouse !

Server TCP Python

Post by Tamaya » Tue Nov 25, 2008 2:30 pm

Hi,

I've got a problem with a TCP Server script... I just want to receive x y coordinates in order to make my 3D objects moves.

I've made it on a thread, but my client can't connect to it. It seems to be a problem on the socket creation:

Here is the code of the script:

Code: Select all

from socket import *
import threading
import time

myHost = "localhost"
myPort = 4242

print("Creating socket ...")
s = socket(AF_INET, SOCK_STREAM)
print("Binding socket ...")
s.bind((myHost, myPort))
print("Now listening ...")
s.listen(1)

class myThread(threading.Thread):
    def __init__(self, name=None):
        threading.Thread.__init__(self, target=self.run, name=name, args=())
        self.run()

    def run(self):
		print("Thread ready")
		while 1:
			connection, address = s.accept()
			print("Connection accepted ...")
			while 1:
				print("recv")
				data = connection.recv(1024)
				print ("data: ")
				print data
				if not data:
					print("stop connection")
					connection.close()
					break


print("Threading ...")
t = myThread("server")

print("Script ended")
Tamaya

robothespian
Posts: 0
Joined: Fri Nov 28, 2008 2:17 pm

Re: Server TCP Python

Post by robothespian » Fri Nov 28, 2008 3:35 pm

Hi,

Does your socket even connect???

Have you tried a simple server + client program to test it - there is one here if not:

http://www.python.org/doc/2.2.3/lib/socket-example.html

If your socket connects and you get "Thread ready" - compiling your code on my machine gets this far, you may be suffering from the socket blocking on the recv call - I am not sure if the socket.accept call blocks, but that may be the same too.

I have set up a socket to allow something else to control my Blender model and here is the stripped out version of my code (you will need to change SOCK_DGRAM, to SOCK_STREAM).

If you set this up, you may "lock up" the Blender interface, so you may have to add an "Exit" button handler - look in this tutorial on how to make a GUI programme and exit your script nicely. (You should use an external Quit / Button handler to set finished = True or similar):

http://feeblemind.tuxfamily.org/dotclea ... -02-en.pdf

I have got to the stage where I can receive data and move bones around, but something - probably threading - seems to be crashing Blender, so watch out...

Here is rough code - check carefully and make a client to talk to it for testing or something.

Code: Select all

# UDP server example!!
import socket, time, struct, sys
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#We allow the call to recvfrom to timeout after 1 second...
server_socket.settimeout(1)
server_socket.bind(("", 7771))

finished = False

while False == finished:
    try:
        data, address = server_socket.recvfrom(256)
        print "data ", data

        #This does not work very well, so you might want to comment it out.
        if True == Blender.Window.TestBreak():
            finished = True
            print "User pressed Escape"
    except socket.error, msg:
       print "socket timeout %s " % (msg)

print "Finished"

Tamaya
Posts: 0
Joined: Sat Nov 22, 2008 3:38 pm
Location: Toulouse !

Post by Tamaya » Thu Dec 04, 2008 2:01 pm

Sorry for be late...

I've made a UDP server, with a try bloc...

Init:

Code: Select all

GameLogic.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
GameLogic.sock.bind(("localhost", 4242))
GameLogic.sock.setblocking(0)
On all frames:

Code: Select all

data = "empty_"

try:
	data, addr = GameLogic.sock.recvfrom(3000)
except:
	pass

if (data != "empty_"):
...
That's work good; If there is no data, the except is called, and so it pass on it and I have no warning on the console.

I will try the GUI too, but my server works good now and I have many work on other parts of my project!
Thanks for your help !!
Tamaya

robothespian
Posts: 0
Joined: Fri Nov 28, 2008 2:17 pm

Game Engine vs Blender

Post by robothespian » Thu Dec 04, 2008 2:52 pm

Hi,

Noticed you are doing a similar thing to what we want.

Do you receive a lot of data through the socket?

We want to animate a robot with data for each of it's armature / bone positions in real time with socket data, but it is slow and Blender "locks up".

Do you use the Game Engine to do this?

I tried Threading, but Blender crashed when it received lots of data - if I remove the thread and just do the socket in a script loop it works, but the interface is "locked up" if there is no incoming data. I can press the ESC key when data is incoming and the script exits, but otherwise it does not...

Do you have any ideas?

Thanks

trickiricki
Posts: 0
Joined: Tue Apr 06, 2010 1:59 pm

Re: Game Engine vs Blender

Post by trickiricki » Tue Apr 06, 2010 2:09 pm

robothespian wrote:Hi,

Noticed you are doing a similar thing to what we want.

Do you receive a lot of data through the socket?

We want to animate a robot with data for each of it's armature / bone positions in real time with socket data, but it is slow and Blender "locks up".

Do you use the Game Engine to do this?

I tried Threading, but Blender crashed when it received lots of data - if I remove the thread and just do the socket in a script loop it works, but the interface is "locked up" if there is no incoming data. I can press the ESC key when data is incoming and the script exits, but otherwise it does not...

Do you have any ideas?

Thanks
sorry for resurecting this old thread, but i have the same problem with a locked blender while using threads... how did u managed the problem robot?
my question can be found here:
http://blenderartists.org/forum/showthr ... ost1603276

stiv
Posts: 0
Joined: Tue Aug 05, 2003 7:58 am
Location: 45N 86W

Post by stiv » Tue Apr 06, 2010 6:15 pm

You need to do non-blocking I/O.

Due to the Global Interpreter Lock (GIL), Python threads execute in an interleaved one at a time fashion. Anytime a thread blocks, the whole mess stalls.

trickiricki
Posts: 0
Joined: Tue Apr 06, 2010 1:59 pm

Post by trickiricki » Wed Apr 07, 2010 12:05 pm

stiv wrote:You need to do non-blocking I/O.

Due to the Global Interpreter Lock (GIL), Python threads execute in an interleaved one at a time fashion. Anytime a thread blocks, the whole mess stalls.
thanks for your answer stiv! i understand what you mean, but can't solve the problem.
here is a short test passage from the code:

Code: Select all

import threading

class BlenderThread(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)

	def run(self):
		import Blender
		import time

		def add_mesh_to_scene(mesh, loc, name):
			obj = Blender.Object.New('Mesh',name)
			obj.link(mesh)
			myScene = Blender.Scene.GetCurrent()
			myScene.link(obj)
			obj.setLocation(*loc)
			print "cube drawn to scene"

		def create_cube():
			myMesh = Blender.Mesh.Primitives.Cube(2)
			add_mesh_to_scene(myMesh, [0,0,0], 'Cube')

		print "THREAD: started"
		
		print "THREAD: sleep 5sec"
		time.sleep(5)
		print "THREAD: wake up"

		create_cube()

		Blender.Draw.Draw()
		Blender.Window.RedrawAll()
		Blender.Window.Redraw()
		Blender.Redraw()
		Blender.Scene.GetCurrent().update()

		print "THREAD: sleep 5sec"
		time.sleep(5)
		print "THREAD: wake up"

		print "THREAD: finished"


print "SCRIPT: started"
thread = BlenderThread()

#my_threads = []
#my_threads.append(thread)

thread.start()

#print "SCRIPT: collect thread"
#for t in my_threads:
#	t.join()

print "SCRIPT: finished"
even if i remove the whole remote stuff from my code i'm running in two diffrent problems:
1) my blender window won't get redrawn, when i don't give focus to it or moving my mouse in the focused window
2) i can't operate in blender while a thread is running and the (main) script waits for the thread to end (activate lines 47, 48 and 53, 54)

i think there is an issue with blenders window manager when you don't finish threads correctly with the join-method, blender and the thread don't know each other and interact indirect with each other...

quinput
Posts: 0
Joined: Fri Dec 10, 2010 11:05 pm
Location: Germany

Post by quinput » Fri Dec 10, 2010 11:24 pm

i think there is an issue with blenders window manager when you don't finish threads correctly with the join-method, blender and the thread don't know each other and interact indirect with each other..
I try a similar thing. I would like to to use blender to display data from a external simulation.
The problem seems to be that after the regular script has finished and only the threads are running that we have no longer access to bpy.ops.*

But bpy.data is still accessible. So I can set a custom property. And this property can be read inside of BGE. No ideal solution, but this could work.

Better would be if we could inject a cmd in the main event loop if we run a background python thread.

ldo
Posts: 0
Joined: Sun Nov 07, 2010 11:30 pm
Location: Hamilton, New Zealand

Post by ldo » Tue Dec 14, 2010 9:34 am

Generally you should avoid using threading within an addon to a host application, unless the host application explicitly supports it. I don’t recall any mention anywhere that Blender supports threads within addon scripts. So don’t do it.

quinput
Posts: 0
Joined: Fri Dec 10, 2010 11:05 pm
Location: Germany

Post by quinput » Tue Dec 14, 2010 9:27 pm

ldo wrote:Generally you should avoid using threading within an addon to a host application, unless the host application explicitly supports it. I don’t recall any mention anywhere that Blender supports threads within addon scripts. So don’t do it.
I have used threads long enough that know if I access blender internal stuff direct in a thread that this is a recipe of a disaster. I would need a network interface in the core C part to inject commands in a proper way in main control loop.
But I have seen after some experiments that you can modify the basic rotation and position attributes of objects without much harm. I start inside a script a http server and finish the script. Inside of the http requests I can set the basic attributes.
The source code is here: http://p.quinput.eu/qwiki/Wiki.jsp?page ... te_control
I think this approach could work good enough for some quick and dirty simulation visualization.

Post Reply