client.py 1023 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #!/usr/bin/env python
  2. import sys
  3. import ssl
  4. from os.path import abspath, dirname
  5. basepath = abspath(dirname(abspath(__file__)) + '/..')
  6. sys.path.insert(0, basepath)
  7. from websocket import websocket
  8. from connection import Connection
  9. from message import TextMessage
  10. from errors import SocketClosed
  11. ADDR = ('localhost', 8000)
  12. class EchoClient(Connection):
  13. def onopen(self):
  14. print 'Connection established, sending "foo"'
  15. self.send(TextMessage('foo'))
  16. def onmessage(self, msg):
  17. print 'Received', msg
  18. self.close(None, 'response received')
  19. def onerror(self, e):
  20. print 'Error:', e
  21. def onclose(self, code, reason):
  22. print 'Connection closed'
  23. secure = True
  24. if __name__ == '__main__':
  25. scheme = 'wss' if secure else 'ws'
  26. print 'Connecting to %s://%s' % (scheme, '%s:%d' % ADDR)
  27. sock = websocket()
  28. if secure:
  29. sock.enable_ssl(ca_certs='cert.pem', cert_reqs=ssl.CERT_REQUIRED)
  30. sock.connect(ADDR)
  31. EchoClient(sock).receive_forever()