A Csound python server
Here is what we are playing with at the moment, the 'universal server'.
#!/usr/bin/python import select import sys import socket import csnd import threading
This is a multiple-client csound server class. the listener is put in a separate thread
class CsoundServerMult:
This is the listener thread function. It just waits for TCP connections
def listen(self):
while not self.end:
print 'waiting for connections..'
self.socks.listen(32)
c, a = self.socks.accept()
if self.end:
print 'exiting...'
else:
print 'Connected to', a
self.conn.append(c)
self.addr.append(a)
self.fd.append(c.fileno())
self.cnt =+ 1
Server start-up:eventually setblocking should be made 0
def __init__(self, port=40002):
self.end = False
self.port = port
self.socks = socket.socket()
self.socks.bind((, self.port))
self.conn = list()
self.addr = list()
self.fd = list()
self.cnt = 0
self.socks.setblocking(1)
print "Csound Python server@%s:%d" % (socket.gethostname(), port)
self.listener = threading.Thread(None,self.listen)
self.listener.start()
This is the interpreter function. If something is seen on the socket, it executes it as Python code
def interpret(self):
This runs the universal orchestra (univorc.csd) and starts the performance. Eventually, we will have to cron a csound instance reset and re-compile after a while to clear up memory.
csound = csnd.Csound()
perf = csnd.CsoundPerformanceThread(csound)
csound.Compile('univorc.csd')
perf.Play()
This is the interpreter loop:
while not self.end:
r,w,x = select.select(self.fd,[],[], 0)
for i in r:
try:
socks = socket.fromfd(i,socket.AF_INET,socket.SOCK_STREAM)
data = socks.recv(256)
exec data
except:
print "exception in code: " + data
This is the shut-off function. It is a bit of a hack, because the listening thread is blocked at socket.listen(). So we need to unblock it by making a connection, then it can quit the loop and exit
def off(self):
self.end = True
sc = socket.socket()
sc.connect(('localhost',self.port))
sc.close()
for i in self.conn:
i.close()
self.end = True
self.socks.close()
The script can run as the 'main' application or the CsoundServerMult class can be re-used by another program.
if __name__=="__main__":
if len(sys.argv) == 2:
s = CsoundServerMult(int(sys.argv[1]))
else:
s = CsoundServerMult()
s.interpret()