- 001
- 002
- 003
- 004
- 005
- 006
- 007
- 008
- 009
- 010
- 011
- 012
- 013
- 014
- 015
- 016
- 017
- 018
- 019
- 020
- 021
- 022
- 023
- 024
- 025
- 026
- 027
- 028
- 029
- 030
- 031
- 032
- 033
- 034
- 035
- 036
- 037
- 038
- 039
- 040
- 041
- 042
- 043
- 044
- 045
- 046
- 047
- 048
- 049
- 050
- 051
- 052
- 053
- 054
- 055
- 056
- 057
- 058
- 059
- 060
- 061
- 062
- 063
- 064
- 065
- 066
- 067
- 068
- 069
- 070
- 071
- 072
- 073
- 074
- 075
- 076
- 077
- 078
- 079
- 080
- 081
- 082
- 083
- 084
- 085
- 086
- 087
- 088
- 089
- 090
- 091
- 092
- 093
- 094
- 095
- 096
- 097
- 098
- 099
- 100
class Stream(object):
def __init__(self, generator):
object.__init__(self)
self.data = ''
self.generator = generator
self.closed = False
generator.subscribe(self)
def update(self, data):
self.data += data
def read(self):
if self.closed: return None
data = self.data
self.data = ''
return data
def close(self):
self.generator.unsubscribe(self)
self.closed = True
self.data = ''
class Server(dispatcher, dict):
writable = lambda x: False
def __init__(self, host = None, port = 0xB00B):
dispatcher.__init__(self)
self.create_socket(AF_INET, SOCK_STREAM)
dict.__init__(self, {self.fileno(): self})
self.set_reuse_addr()
self.bind((host, port))
self.listen(0xA)
self.dataSource = PiGenerator()
def removeClient(self, client):
del self[client.fileno()]
def handle_accept(self):
sock, (host, port) = self.accept()
print 'new client from %s:%d' % (host, port)
stream = Stream(self.dataSource)
self[sock.fileno()] = Client(sock, self, stream)
def handle_error(self):
print 'Server error: %s' % sys.exc_value
sys.exit(1)
class Client(dispatcher):
readable = lambda x: False
def __init__(self, sock, server, stream):
dispatcher.__init__(self, sock)
self.server = server
self.stream = stream
self.buffer = ''
def handle_error(self):
print 'Client error: %s' % sys.exc_value
import traceback
print traceback.format_exc(1000)
sys.exit(1)
def handle_write(self):
sent = self.send(self.buffer)
self.buffer = self.buffer[sent:]
def handle_expt(self):
print 'client dropped connection'
self.close()
def close(self):
self.server.removeClient(self)
self.stream.close()
self.buffer = ''
dispatcher.close(self)
def writable(self):
data = self.stream.read()
if data == None:
print 'client finished reading'
self.close()
return False
self.buffer += data
return len(self.buffer) > 0
def main():
try:
asyncore.loop(0.1, True, Server('127.0.0.1'))
except KeyboardInterrupt:
print '\nBye :-*'
sys.exit(0)
if __name__ == '__main__':
main()
TeaBag 23.05.2017 23:48 # −6
Masha-Rostova 07.06.2017 15:41 # 0