1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
#!/usr/bin/python
import select
import sys
import socket
import threading
import time
import os.path
import csnd
# this is a multiple-client csound server
# the listener is put in a separate thread
class CsoundServerMult:
# server start-up
def __init__(self, addr):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind(addr)
self.size = 1024
print "*** CsServer: Csound Python server listening at: @%s:%d" % (ipaddr, port)
self.server.listen(32)
self.input = [self.server,sys.stdin]
self.running = 1
# this is the interpreter function
# if something is seen on the socket
# it executes it as Python code
def interpret(self):
# run the universal orchestra
csound = csnd.Csound()
perf = csnd.CsoundPerformanceThread(csound)
csound.Compile(os.path.join(_DIR_CSSERVER, 'univorc.csd'))
perf.Play()
while self.running:
inputready,outputready,exceptready = select.select(self.input,[],[])
for s in inputready:
if s == self.server:
# handle the server socket
client, address = self.server.accept()
print'*** CsServer: Client has been accepted on: ',address
self.input.append(client)
elif s == sys.stdin:
# handle standard input
junk = sys.stdin.readline()
csound.SetChannel('udprecv.0.on', 0)
perf.Stop()
perf.Join()
csound.Reset()
csound = None
print '*** CsServer: The csound instance has been reset successfully.'
self.running = 0
else:
# handle all other sockets
data = s.recv(self.size)
print data
if data.strip('\n') == 'off()':
csound.SetChannel('udprecv.0.on', 0)
perf.Stop()
perf.Join()
csound.Reset()
csound = None
print '*** CsServer: The csound instance has been reset successfully.'
self.running = 0
elif data:
try:
exec data
except:
print "exception in code: " + data
else:
print '*** CsServer: remove socket: ', s.fileno()
s.close()
self.input.remove(s)
for i in self.input:
i.close()
self.input.remove(i)
self.server.close()
print '*** CsServer: The server has been closed.'
if __name__=="__main__":
if len(sys.argv) > 1:
ipaddr = sys.argv[1]
else:
ipaddr = 'localhost'
if len(sys.argv) > 2:
port = int(sys.argv[2])
else:
port = 40002
_DIR_CSSERVER = os.path.join(os.path.dirname(__file__))
s = CsoundServerMult((ipaddr, port))
s.interpret()
|