package tcp socket implementation for more flexible use
This commit is contained in:
@@ -6,19 +6,19 @@ import time
|
||||
class TcpClient(asyncore.dispatcher):
|
||||
queue = []
|
||||
|
||||
def __init__(self, host, port):
|
||||
def __init__(self, host, port, bufferSize = 1000):
|
||||
asyncore.dispatcher.__init__(self)
|
||||
self.address = (host, port)
|
||||
|
||||
self.bufferSize = bufferSize
|
||||
|
||||
def handle_connect(self):
|
||||
print "Connected to server"
|
||||
|
||||
def handle_close(self):
|
||||
self.close()
|
||||
|
||||
|
||||
def handle_read(self):
|
||||
response = self.recv(8192)
|
||||
print "Received:", response
|
||||
self.input(self.recv(self.bufferSize))
|
||||
|
||||
def writable(self):
|
||||
return (len(self.queue) > 0)
|
||||
@@ -38,15 +38,22 @@ class TcpClient(asyncore.dispatcher):
|
||||
self.close()
|
||||
self.thread.join()
|
||||
|
||||
def _send(self, data):
|
||||
def write(self, data):
|
||||
self.queue.append(data)
|
||||
|
||||
def input(self, data):
|
||||
pass
|
||||
|
||||
def client_input(data):
|
||||
print 'client:', data
|
||||
|
||||
if __name__ == '__main__':
|
||||
client = TcpClient('localhost', 10000)
|
||||
client.input = client_input
|
||||
client.start()
|
||||
|
||||
for i in range(1, 50):
|
||||
client.send('client #%d' % i)
|
||||
|
||||
for i in range(1, 5000):
|
||||
client.write('client #%d' % i)
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
client.stop()
|
||||
Reference in New Issue
Block a user