Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Jul 8th, 2011  |  syntax: Python  |  size: 1.05 KB  |  views: 337  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import websocket, thread
  2. import simplejson as json
  3.  
  4. SOCKET_IO_HOST = "127.0.0.1"
  5. SOCKET_IO_PORT = 8080
  6. socket_io_url = 'http://' + SOCKET_IO_HOST + ':' + str(SOCKET_IO_PORT) + '/socket.io/websocket'
  7. def encode_for_socketio(message):
  8.     """
  9.    Encode 'message' string or dictionary to be able
  10.    to be transported via a Python WebSocket client to
  11.    a Socket.IO server (which is capable of receiving
  12.    WebSocket communications). This method taken from
  13.    gevent-socketio.
  14.    """
  15.     MSG_FRAME = "~m~"
  16.     HEARTBEAT_FRAME = "~h~"
  17.     JSON_FRAME = "~j~"
  18.  
  19.     if isinstance(message, basestring):
  20.             encoded_msg = message
  21.     elif isinstance(message, (object, dict)):
  22.             return encode_for_socketio(JSON_FRAME + json.dumps(message))
  23.     else:
  24.             raise ValueError("Can't encode message.")
  25.  
  26.     return MSG_FRAME + str(len(encoded_msg)) + MSG_FRAME + encoded_msg
  27. ws = None
  28.  
  29. def sendMsg(m=''):
  30.         global ws
  31.         if ws == None:
  32.                 ws = websocket.create_connection(socket_io_url)
  33.         ws.send(encode_for_socketio({'message':m}))