SHOW:
|
|
- or go back to the newest paste.
| 1 | - | #!/usr/bin/python |
| 1 | + | #!/usr/bin/env python |
| 2 | ||
| 3 | import socket | |
| 4 | from threading import Thread | |
| 5 | from Queue import Queue | |
| 6 | from time import sleep | |
| 7 | import json | |
| 8 | ||
| 9 | class ClientThread(Thread): | |
| 10 | def __init__(self, connection): | |
| 11 | super(ClientThread, self).__init__() | |
| 12 | ||
| 13 | self.recv = connection.recv | |
| 14 | self.send = connection.send | |
| 15 | self.que = Queue() | |
| 16 | ||
| 17 | def run(self): | |
| 18 | while True: | |
| 19 | cmd = self.que.get() | |
| 20 | self.send(json.dumps(cmd)) | |
| 21 | if cmd == 'exit': | |
| 22 | break | |
| 23 | ||
| 24 | class Control: | |
| 25 | def __init__(self): | |
| 26 | print 'Started server script.' | |
| 27 | ||
| 28 | s = Server() | |
| 29 | s.start() | |
| 30 | ||
| 31 | self.que = s.que | |
| 32 | self.loop() | |
| 33 | ||
| 34 | def loop(self): | |
| 35 | while True: | |
| 36 | cmd = raw_input('> ')
| |
| 37 | if cmd == 'exit': | |
| 38 | self.que.put(cmd) | |
| 39 | break | |
| 40 | else: | |
| 41 | self.que.put(cmd) | |
| 42 | ||
| 43 | class Server(Thread): | |
| 44 | clients = [] | |
| 45 | def __init__(self): | |
| 46 | super(Server, self).__init__() | |
| 47 | self.que = Queue() | |
| 48 | ||
| 49 | def run(self): | |
| 50 | self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| 51 | self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
| 52 | server_address = ("localhost", 9006)
| |
| 53 | ||
| 54 | self.server.bind(server_address) | |
| 55 | self.server.listen(5) | |
| 56 | ||
| 57 | while True: | |
| 58 | if not self.que.empty(): | |
| 59 | cmd = self.que.get() | |
| 60 | ||
| 61 | if cmd.split(' ')[0] == 'accept':
| |
| 62 | self.loop(int(cmd.split(' ')[1]))
| |
| 63 | continue | |
| 64 | ||
| 65 | for client in self.clients: | |
| 66 | client.que.put(cmd) | |
| 67 | ||
| 68 | if cmd == 'exit': | |
| 69 | break | |
| 70 | else: | |
| 71 | sleep(0.1) | |
| 72 | ||
| 73 | for client in self.clients: | |
| 74 | client.join() | |
| 75 | ||
| 76 | def loop(self, iterations): | |
| 77 | for i in xrange(iterations): | |
| 78 | #print '\nAwaiting %i clients.' % num | |
| 79 | connection, client_address = self.server.accept() | |
| 80 | c = ClientThread(connection) | |
| 81 | self.clients.append(c) | |
| 82 | c.start() | |
| 83 | ||
| 84 | if __name__ == '__main__': | |
| 85 | - | server = ServerControl() |
| 85 | + | c = Control() |