示例#1
0
    def test_receive_message_random_section(self):
        """Test that a compressed message fragmented into lots of chunks is
        correctly received.
        """

        random.seed(a=0)
        payload = b''.join(
            [struct.pack('!B', random.randint(0, 255)) for i in range(1000)])

        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED,
                                    -zlib.MAX_WBITS)
        compressed_payload = compress.compress(payload)
        compressed_payload += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_payload = compressed_payload[:-4]

        # Fragment the compressed payload into lots of frames.
        bytes_chunked = 0
        data = b''
        frame_count = 0

        chunk_sizes = []

        while bytes_chunked < len(compressed_payload):
            # Make sure that
            # - the length of chunks are equal or less than 125 so that we can
            #   use 1 octet length header format for all frames.
            # - at least 10 chunks are created.
            chunk_size = random.randint(
                1,
                min(125,
                    len(compressed_payload) // 10,
                    len(compressed_payload) - bytes_chunked))
            chunk_sizes.append(chunk_size)
            chunk = compressed_payload[bytes_chunked:bytes_chunked +
                                       chunk_size]
            bytes_chunked += chunk_size

            first_octet = 0x00
            if len(data) == 0:
                first_octet = first_octet | 0x42
            if bytes_chunked == len(compressed_payload):
                first_octet = first_octet | 0x80

            data += b'%c%c' % (first_octet, chunk_size | 0x80)
            data += _mask_hybi(chunk)

            frame_count += 1

        self.assertTrue(len(chunk_sizes) > 10)

        # Close frame
        data += b'\x88\x8a' + _mask_hybi(struct.pack('!H', 1000) + b'Good bye')

        extension = common.ExtensionParameter(
            common.PERMESSAGE_DEFLATE_EXTENSION)
        request = _create_request_from_rawdata(
            data, permessage_deflate_request=extension)
        self.assertEqual(payload, msgutil.receive_message(request))

        self.assertEqual(None, msgutil.receive_message(request))
示例#2
0
    def test_receive_message_deflate_stream(self):
        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED,
                                    -zlib.MAX_WBITS)

        data = compress.compress('\x81\x85' + _mask_hybi('Hello'))
        data += compress.flush(zlib.Z_SYNC_FLUSH)
        data += compress.compress('\x81\x89' + _mask_hybi('WebSocket'))
        data += compress.flush(zlib.Z_FINISH)

        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED,
                                    -zlib.MAX_WBITS)

        data += compress.compress('\x81\x85' + _mask_hybi('World'))
        data += compress.flush(zlib.Z_SYNC_FLUSH)
        # Close frame
        data += compress.compress(
            '\x88\x8a' + _mask_hybi(struct.pack('!H', 1000) + 'Good bye'))
        data += compress.flush(zlib.Z_SYNC_FLUSH)

        request = _create_request_from_rawdata(data, deflate_stream=True)
        self.assertEqual('Hello', msgutil.receive_message(request))
        self.assertEqual('WebSocket', msgutil.receive_message(request))
        self.assertEqual('World', msgutil.receive_message(request))

        self.assertFalse(request.drain_received_data_called)

        self.assertEqual(None, msgutil.receive_message(request))

        self.assertTrue(request.drain_received_data_called)
示例#3
0
    def test_receive_message_deflate_frame_client_using_smaller_window(self):
        """Test that frames coming from a client which is using smaller window
        size that the server are correctly received.
        """

        # Using the smallest window bits of 8 for generating input frames.
        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED,
                                    -8)

        data = ''

        # Use a frame whose content is bigger than the clients' DEFLATE window
        # size before compression. The content mainly consists of 'a' but
        # repetition of 'b' is put at the head and tail so that if the window
        # size is big, the head is back-referenced but if small, not.
        payload = 'b' * 64 + 'a' * 1024 + 'b' * 64
        compressed_hello = compress.compress(payload)
        compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_hello = compressed_hello[:-4]
        data += '\xc1%c' % (len(compressed_hello) | 0x80)
        data += _mask_hybi(compressed_hello)

        # Close frame
        data += '\x88\x8a' + _mask_hybi(struct.pack('!H', 1000) + 'Good bye')

        extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
        request = _create_request_from_rawdata(data,
                                               deflate_frame_request=extension)
        self.assertEqual(payload, msgutil.receive_message(request))

        self.assertEqual(None, msgutil.receive_message(request))
示例#4
0
def web_socket_transfer_data(request):
    global connections
    r = request.ws_resource.split('?', 1)
    if len(r) == 1:
        return
    param = cgi.parse_qs(r[1])
    if 'p' not in param:
        return
    page_group = param['p'][0]
    if page_group in connections:
        connections[page_group].add(request)
    else:
        connections[page_group] = set([request])
    message = None
    dataToBroadcast = {}
    try:
        message = msgutil.receive_message(request)
        # notify to client that message is received by server.
        msgutil.send_message(request, message)
        msgutil.receive_message(request)
        dataToBroadcast['message'] = message
        dataToBroadcast['closeCode'] = str(request.ws_close_code)
    finally:
        # request is closed. notify this dataToBroadcast to other WebSockets.
        connections[page_group].remove(request)
        for ws in connections[page_group]:
            msgutil.send_message(ws, json.dumps(dataToBroadcast))
def web_socket_transfer_data(request):
    global connections
    r = request.ws_resource.split('?', 1)
    if len(r) == 1:
        return
    param = cgi.parse_qs(r[1])
    if 'p' not in param:
        return
    page_group = param['p'][0]
    if page_group in connections:
        connections[page_group].add(request)
    else:
        connections[page_group] = set([request])
    message = None
    dataToBroadcast = {}
    try:
        message = msgutil.receive_message(request)
        # notify to client that message is received by server.
        msgutil.send_message(request, message)
        msgutil.receive_message(request)
        dataToBroadcast['message'] = message
        dataToBroadcast['closeCode'] = str(request.ws_close_code)
    finally:
        # request is closed. notify this dataToBroadcast to other WebSockets.
        connections[page_group].remove(request)
        for ws in connections[page_group]:
            msgutil.send_message(ws, json.dumps(dataToBroadcast))
示例#6
0
    def test_receive_message_deflate_stream(self):
        compress = zlib.compressobj(
            zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)

        data = compress.compress('\x81\x85' + _mask_hybi('Hello'))
        data += compress.flush(zlib.Z_SYNC_FLUSH)
        data += compress.compress('\x81\x89' + _mask_hybi('WebSocket'))
        data += compress.flush(zlib.Z_FINISH)

        compress = zlib.compressobj(
            zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)

        data += compress.compress('\x81\x85' + _mask_hybi('World'))
        data += compress.flush(zlib.Z_SYNC_FLUSH)
        # Close frame
        data += compress.compress(
            '\x88\x8a' + _mask_hybi(struct.pack('!H', 1000) + 'Good bye'))
        data += compress.flush(zlib.Z_SYNC_FLUSH)

        request = _create_request_from_rawdata(data, deflate_stream=True)
        self.assertEqual('Hello', msgutil.receive_message(request))
        self.assertEqual('WebSocket', msgutil.receive_message(request))
        self.assertEqual('World', msgutil.receive_message(request))

        self.assertFalse(request.drain_received_data_called)

        self.assertEqual(None, msgutil.receive_message(request))

        self.assertTrue(request.drain_received_data_called)
示例#7
0
    def test_receive_message_deflate_frame(self):
        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)

        data = ""

        compressed_hello = compress.compress("Hello")
        compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_hello = compressed_hello[:-4]
        data += "\xc1%c" % (len(compressed_hello) | 0x80)
        data += _mask_hybi(compressed_hello)

        compressed_websocket = compress.compress("WebSocket")
        compressed_websocket += compress.flush(zlib.Z_FINISH)
        compressed_websocket += "\x00"
        data += "\xc1%c" % (len(compressed_websocket) | 0x80)
        data += _mask_hybi(compressed_websocket)

        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)

        compressed_world = compress.compress("World")
        compressed_world += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_world = compressed_world[:-4]
        data += "\xc1%c" % (len(compressed_world) | 0x80)
        data += _mask_hybi(compressed_world)

        # Close frame
        data += "\x88\x8a" + _mask_hybi(struct.pack("!H", 1000) + "Good bye")

        extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
        request = _create_request_from_rawdata(data, deflate_frame_request=extension)
        self.assertEqual("Hello", msgutil.receive_message(request))
        self.assertEqual("WebSocket", msgutil.receive_message(request))
        self.assertEqual("World", msgutil.receive_message(request))

        self.assertEqual(None, msgutil.receive_message(request))
示例#8
0
    def test_receive_message_permessage_deflate_compression(self):
        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)

        data = ""

        compressed_hello = compress.compress("HelloWebSocket")
        compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_hello = compressed_hello[:-4]
        split_position = len(compressed_hello) / 2
        data += "\x41%c" % (split_position | 0x80)
        data += _mask_hybi(compressed_hello[:split_position])

        data += "\x80%c" % ((len(compressed_hello) - split_position) | 0x80)
        data += _mask_hybi(compressed_hello[split_position:])

        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)

        compressed_world = compress.compress("World")
        compressed_world += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_world = compressed_world[:-4]
        data += "\xc1%c" % (len(compressed_world) | 0x80)
        data += _mask_hybi(compressed_world)

        # Close frame
        data += "\x88\x8a" + _mask_hybi(struct.pack("!H", 1000) + "Good bye")

        extension = common.ExtensionParameter(common.PERMESSAGE_COMPRESSION_EXTENSION)
        extension.add_parameter("method", "deflate")
        request = _create_request_from_rawdata(data, permessage_compression_request=extension)
        self.assertEqual("HelloWebSocket", msgutil.receive_message(request))
        self.assertEqual("World", msgutil.receive_message(request))

        self.assertEqual(None, msgutil.receive_message(request))
示例#9
0
    def test_receive_message_deflate_frame_client_using_smaller_window(self):
        """Test that frames coming from a client which is using smaller window
        size that the server are correctly received.
        """

        # Using the smallest window bits of 8 for generating input frames.
        compress = zlib.compressobj(
            zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -8)

        data = ''

        # Use a frame whose content is bigger than the clients' DEFLATE window
        # size before compression. The content mainly consists of 'a' but
        # repetition of 'b' is put at the head and tail so that if the window
        # size is big, the head is back-referenced but if small, not.
        payload = 'b' * 64 + 'a' * 1024 + 'b' * 64
        compressed_hello = compress.compress(payload)
        compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_hello = compressed_hello[:-4]
        data += '\xc1%c' % (len(compressed_hello) | 0x80)
        data += _mask_hybi(compressed_hello)

        # Close frame
        data += '\x88\x8a' + _mask_hybi(struct.pack('!H', 1000) + 'Good bye')

        extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
        request = _create_request_from_rawdata(
            data, deflate_frame_request=extension)
        self.assertEqual(payload, msgutil.receive_message(request))

        self.assertEqual(None, msgutil.receive_message(request))
示例#10
0
def web_socket_transfer_data(request):
  if request.ws_protocol == "test 2.1" or request.ws_protocol == "test 2.2":
    msgutil.close_connection(request)
  elif request.ws_protocol == "test 6":
    resp = "wrong message"
    if msgutil.receive_message(request) == "1":
      resp = "2"
    msgutil.send_message(request, resp.decode('utf-8'))
    resp = "wrong message"
    if msgutil.receive_message(request) == "3":
      resp = "4"
    msgutil.send_message(request, resp.decode('utf-8'))
    resp = "wrong message"
    if msgutil.receive_message(request) == "5":
      resp = "あいうえお"
    msgutil.send_message(request, resp.decode('utf-8'))
  elif request.ws_protocol == "test 7":
    try:
      while not request.client_terminated:
        msgutil.receive_message(request)
    except msgutil.ConnectionTerminatedException, e:
      pass
    msgutil.send_message(request, "server data")
    msgutil.send_message(request, "server data")
    msgutil.send_message(request, "server data")
    msgutil.send_message(request, "server data")
    msgutil.send_message(request, "server data")
    time.sleep(30)
    msgutil.close_connection(request, True)
示例#11
0
    def test_receive_medium_message(self):
        payload = 'a' * 126
        request = _create_request(('\x81\xfe\x00\x7e', payload))
        self.assertEqual(payload, msgutil.receive_message(request))

        payload = 'a' * ((1 << 16) - 1)
        request = _create_request(('\x81\xfe\xff\xff', payload))
        self.assertEqual(payload, msgutil.receive_message(request))
示例#12
0
 def test_receive_message_discard(self):
     request = _create_request(
         ("\x8f\x86", "IGNORE"), ("\x81\x85", "Hello"), ("\x8f\x89", "DISREGARD"), ("\x81\x86", "World!")
     )
     self.assertRaises(msgutil.UnsupportedFrameException, msgutil.receive_message, request)
     self.assertEqual("Hello", msgutil.receive_message(request))
     self.assertRaises(msgutil.UnsupportedFrameException, msgutil.receive_message, request)
     self.assertEqual("World!", msgutil.receive_message(request))
示例#13
0
    def test_receive_message(self):
        request = _create_request(("\x81\x85", "Hello"), ("\x81\x86", "World!"))
        self.assertEqual("Hello", msgutil.receive_message(request))
        self.assertEqual("World!", msgutil.receive_message(request))

        payload = "a" * 125
        request = _create_request(("\x81\xfd", payload))
        self.assertEqual(payload, msgutil.receive_message(request))
示例#14
0
    def test_receive_medium_message(self):
        payload = 'a' * 126
        request = _create_request(('\x81\xfe\x00\x7e', payload))
        self.assertEqual(payload, msgutil.receive_message(request))

        payload = 'a' * ((1 << 16) - 1)
        request = _create_request(('\x81\xfe\xff\xff', payload))
        self.assertEqual(payload, msgutil.receive_message(request))
示例#15
0
    def test_receive_unsolicited_pong(self):
        # Unsolicited pong is allowed from HyBi 07.
        request = _create_request(('\x8a\x85', 'Hello'), ('\x81\x85', 'World'))
        msgutil.receive_message(request)

        request = _create_request(('\x8a\x85', 'Hello'), ('\x81\x85', 'World'))
        msgutil.send_ping(request, 'Jumbo')
        # Body mismatch.
        msgutil.receive_message(request)
示例#16
0
    def test_receive_unsolicited_pong(self):
        # Unsolicited pong is allowed from HyBi 07.
        request = _create_request(("\x8a\x85", "Hello"), ("\x81\x85", "World"))
        msgutil.receive_message(request)

        request = _create_request(("\x8a\x85", "Hello"), ("\x81\x85", "World"))
        msgutil.send_ping(request, "Jumbo")
        # Body mismatch.
        msgutil.receive_message(request)
示例#17
0
    def test_receive_message(self):
        request = _create_request(
            ('\x81\x85', 'Hello'), ('\x81\x86', 'World!'))
        self.assertEqual('Hello', msgutil.receive_message(request))
        self.assertEqual('World!', msgutil.receive_message(request))

        payload = 'a' * 125
        request = _create_request(('\x81\xfd', payload))
        self.assertEqual(payload, msgutil.receive_message(request))
示例#18
0
    def test_receive_message(self):
        request = _create_request(('\x81\x85', 'Hello'),
                                  ('\x81\x86', 'World!'))
        self.assertEqual('Hello', msgutil.receive_message(request))
        self.assertEqual('World!', msgutil.receive_message(request))

        payload = 'a' * 125
        request = _create_request(('\x81\xfd', payload))
        self.assertEqual(payload, msgutil.receive_message(request))
示例#19
0
    def test_receive_message(self):
        request = _create_request((b'\x81\x85', b'Hello'),
                                  (b'\x81\x86', b'World!'))
        self.assertEqual('Hello', msgutil.receive_message(request))
        self.assertEqual('World!', msgutil.receive_message(request))

        payload = b'a' * 125
        request = _create_request((b'\x81\xfd', payload))
        self.assertEqual(payload.decode('UTF-8'),
                         msgutil.receive_message(request))
示例#20
0
 def test_receive_message_discard(self):
     request = _create_request(
         ('\x8f\x86', 'IGNORE'), ('\x81\x85', 'Hello'),
         ('\x8f\x89', 'DISREGARD'), ('\x81\x86', 'World!'))
     self.assertRaises(msgutil.UnsupportedFrameException,
                       msgutil.receive_message, request)
     self.assertEqual('Hello', msgutil.receive_message(request))
     self.assertRaises(msgutil.UnsupportedFrameException,
                       msgutil.receive_message, request)
     self.assertEqual('World!', msgutil.receive_message(request))
示例#21
0
 def test_receive_message_discard(self):
     request = _create_request(
         ('\x8f\x86', 'IGNORE'), ('\x81\x85', 'Hello'),
         ('\x8f\x89', 'DISREGARD'), ('\x81\x86', 'World!'))
     self.assertRaises(msgutil.UnsupportedFrameException,
                       msgutil.receive_message, request)
     self.assertEqual('Hello', msgutil.receive_message(request))
     self.assertRaises(msgutil.UnsupportedFrameException,
                       msgutil.receive_message, request)
     self.assertEqual('World!', msgutil.receive_message(request))
示例#22
0
    def test_receive_unsolicited_pong(self):
        # Unsolicited pong is allowed from HyBi 07.
        request = _create_request(
            ('\x8a\x85', 'Hello'), ('\x81\x85', 'World'))
        msgutil.receive_message(request)

        request = _create_request(
            ('\x8a\x85', 'Hello'), ('\x81\x85', 'World'))
        msgutil.send_ping(request, 'Jumbo')
        # Body mismatch.
        msgutil.receive_message(request)
示例#23
0
def web_socket_transfer_data(request):
    global connections
    connections[request] = True
    socketName = None
    try:
        socketName = msgutil.receive_message(request)
        # notify to client that socketName is received by server.
        msgutil.send_message(request, socketName)
        msgutil.receive_message(request)  # wait, and exception by close.
    finally:
        # request is closed. notify this socketName to other web sockets.
        del connections[request]
        for ws in connections.keys():
            msgutil.send_message(ws, socketName + ': receive next message')
def web_socket_transfer_data(request):
    global connections
    connections[request] = True
    socketName = None
    try:
        socketName = msgutil.receive_message(request)
        # notify to client that socketName is received by server.
        msgutil.send_message(request, socketName)
        msgutil.receive_message(request)  # wait, and exception by close.
        socketName = socketName + ': receive next message'
    finally:
        # request is closed. notify this socketName to other web sockets.
        del connections[request]
        for ws in connections.keys():
            msgutil.send_message(ws, socketName)
示例#25
0
    def test_receive_ping(self):
        """Tests receiving a ping control frame."""
        def handler(request, message):
            request.called = True

        # Stream automatically respond to ping with pong without any action
        # by application layer.
        request = _create_request(('\x89\x85', 'Hello'), ('\x81\x85', 'World'))
        self.assertEqual('World', msgutil.receive_message(request))
        self.assertEqual('\x8a\x05Hello', request.connection.written_data())

        request = _create_request(('\x89\x85', 'Hello'), ('\x81\x85', 'World'))
        request.on_ping_handler = handler
        self.assertEqual('World', msgutil.receive_message(request))
        self.assertTrue(request.called)
示例#26
0
def web_socket_transfer_data(request):
    # request.connection.remote_ip
    UDPSock = socket(AF_INET,SOCK_DGRAM)
    r = redis.Redis()
    timelim = time.time() + timeout
    while True:
        data = msgutil.receive_message(request)
        if time.time() > timelim:
            print "A send timed out"
            UDPSock.close()
            r.disconnect()
            break
            
        if data == __KillerWords__:
            print "A send did suicide"
            UDPSock.close()
            r.disconnect()
            break
            
        timelim = time.time() + timeout
        data = data.replace ('<','&lt;').replace('>','&gt;')[:max_msg_size]
        message = '%s|user%s' % (time.time(), data)
        r.push ('msgs',message,head=True)
        if (message.find('@baka ') > 0):
            # send a copy to bokkabot
            UDPSock.sendto(message,addr)
示例#27
0
    def test_receive_ping(self):
        """Tests receiving a ping control frame."""

        def handler(request, message):
            request.called = True

        # Stream automatically respond to ping with pong without any action
        # by application layer.
        request = _create_request(("\x89\x85", "Hello"), ("\x81\x85", "World"))
        self.assertEqual("World", msgutil.receive_message(request))
        self.assertEqual("\x8a\x05Hello", request.connection.written_data())

        request = _create_request(("\x89\x85", "Hello"), ("\x81\x85", "World"))
        request.on_ping_handler = handler
        self.assertEqual("World", msgutil.receive_message(request))
        self.assertTrue(request.called)
示例#28
0
    def test_receive_message_deflate_frame_comp_bit(self):
        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED,
                                    -zlib.MAX_WBITS)

        data = ''

        compressed_hello = compress.compress('Hello')
        compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_hello = compressed_hello[:-4]
        data += '\xc1%c' % (len(compressed_hello) | 0x80)
        data += _mask_hybi(compressed_hello)

        data += '\x81\x85' + _mask_hybi('Hello')

        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED,
                                    -zlib.MAX_WBITS)

        compressed_2nd_hello = compress.compress('Hello')
        compressed_2nd_hello += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_2nd_hello = compressed_2nd_hello[:-4]
        data += '\xc1%c' % (len(compressed_2nd_hello) | 0x80)
        data += _mask_hybi(compressed_2nd_hello)

        extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
        request = _create_request_from_rawdata(data,
                                               deflate_frame_request=extension)
        for i in xrange(3):
            self.assertEqual('Hello', msgutil.receive_message(request))
示例#29
0
 def test_receive_fragments(self):
     request = _create_request(
         ('\x01\x85', 'Hello'),
         ('\x00\x81', ' '),
         ('\x00\x85', 'World'),
         ('\x80\x81', '!'))
     self.assertEqual('Hello World!', msgutil.receive_message(request))
示例#30
0
def web_socket_transfer_data(request):
	global _status_
	_status_ = _OPEN_
	arr = ()
	thread.start_new_thread(tail(file, 0.5, request).run, arr)
	while True:
		try:
			#######################################################
			# Note::
			# mesgutil.receive_message() returns 'unicode', so
			# if you want to treated as 'string', use encode('utf-8')
			#######################################################
			line = msgutil.receive_message(request).encode('utf-8')
			
			if line == _HEARTBEAT_:
				continue
		
			f = open(file, 'a')
			f.write(line+"\n")
			os.fsync(f.fileno())
			f.flush()
			f.close
			
		except Exception:
			_status_ = _CLOSING_
			# wait until _status_ change.
			i = 0
			while _status_ == _CLOSING_:
				time.sleep(0.5)
				i += 1
				if i > 10:
					break
			return
示例#31
0
 def test_receive_fragments_unicode(self):
     # UTF-8 encodes U+6f22 into e6bca2 and U+5b57 into e5ad97.
     request = _create_request(
         ('\x01\x82', '\xe6\xbc'),
         ('\x00\x82', '\xa2\xe5'),
         ('\x80\x82', '\xad\x97'))
     self.assertEqual(u'\u6f22\u5b57', msgutil.receive_message(request))
示例#32
0
def web_socket_transfer_data(request):
    from urlparse import urlparse
    from urlparse import parse_qs
    #requests.append(request)
    url = urlparse(request.get_uri())
    query = parse_qs(url.query)
    if query.has_key('projectName'):
        projectNames = query["projectName"]
        if len(projectNames) == 1:
            projectName = projectNames[0]
            if not rooms.has_key(projectName):
                rooms[projectName] = []
            rooms[projectName].append(request)
    while True:
        try:
            message = msgutil.receive_message(request)
        except Exception:
            return
        #for req in requests:
        #    try:
        #        msgutil.send_message(req, message)
        #    except Exception:
        #        requests.remove(req)
        for req in rooms[projectName]:
            try:
                msgutil.send_message(req, message)
            except Exception:
                rooms[projectName].remove(req)
                if len(rooms[projectName]) == 0:
                    del rooms[projectName]
示例#33
0
    def test_receive_message_deflate_frame_comp_bit(self):
        compress = zlib.compressobj(
            zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)

        data = ''

        compressed_hello = compress.compress('Hello')
        compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_hello = compressed_hello[:-4]
        data += '\xc1%c' % (len(compressed_hello) | 0x80)
        data += _mask_hybi(compressed_hello)

        data += '\x81\x85' + _mask_hybi('Hello')

        compress = zlib.compressobj(
            zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS)

        compressed_2nd_hello = compress.compress('Hello')
        compressed_2nd_hello += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_2nd_hello = compressed_2nd_hello[:-4]
        data += '\xc1%c' % (len(compressed_2nd_hello) | 0x80)
        data += _mask_hybi(compressed_2nd_hello)

        extension = common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION)
        request = _create_request_from_rawdata(
            data, deflate_frame_request=extension)
        for i in xrange(3):
            self.assertEqual('Hello', msgutil.receive_message(request))
示例#34
0
    def test_receive_length_not_encoded_using_minimal_number_of_bytes(self):
        # Log warning on receiving bad payload length field that doesn't use
        # minimal number of bytes but continue processing.

        payload = "a"
        # 1 byte can be represented without extended payload length field.
        request = _create_request(("\x81\xff\x00\x00\x00\x00\x00\x00\x00\x01", payload))
        self.assertEqual(payload, msgutil.receive_message(request))
示例#35
0
def web_socket_transfer_data(request):
	while True:
		s = msgutil.receive_message(request)
		for connect in arr:
			try:
				msgutil.send_message(connect, s)
			except:
				arr.remove(connect)
示例#36
0
def web_socket_transfer_data(request):
    while True:
        line = msgutil.receive_message(request)
        if line == b'exit':
            return

        if line is not None:
            request.connection.write(line)
def web_socket_transfer_data(request):
    global connections
    connections[request] = True
    message = None
    dataToBroadcast = {}
    try:
        message = msgutil.receive_message(request)
        # notify to client that message is received by server.
        msgutil.send_message(request, message)
        msgutil.receive_message(request)  # wait, and exception by close.
        dataToBroadcast["message"] = message
        dataToBroadcast["closeCode"] = str(request.ws_close_code)
    finally:
        # request is closed. notify this dataToBroadcast to other web sockets.
        del connections[request]
        for ws in connections.keys():
            msgutil.send_message(ws, json.dumps(dataToBroadcast))
def web_socket_transfer_data(request):
    while True:
        rcvd = msgutil.receive_message(request)
        opcode = request.ws_stream.get_last_received_opcode()
        if (opcode == common.OPCODE_BINARY):
            msgutil.send_message(request, rcvd, binary=True)
        elif (opcode == common.OPCODE_TEXT):
            msgutil.send_message(request, rcvd)
def web_socket_transfer_data(request):
  while True:
    rcvd = msgutil.receive_message(request)
    opcode = request.ws_stream.get_last_received_opcode()
    if (opcode == common.OPCODE_BINARY):
      msgutil.send_message(request, rcvd, binary=True)
    elif (opcode == common.OPCODE_TEXT):
      msgutil.send_message(request, rcvd)
示例#40
0
def web_socket_transfer_data(request):
    global connections
    connections[request] = True
    socketName = None
    receivedException = True
    try:
        socketName = msgutil.receive_message(request)
        msgutil.send_message(request, socketName)
        msgutil.receive_message(request)  # wait, and exception by close.
        receivedException = False
    finally:
        # We keep track of whether we have an exception.
        del connections[request]
        for ws in connections.keys():
            msgutil.send_message(
                ws, "Closed by exception"
                if receivedException else "Closed without exception")
示例#41
0
def web_socket_transfer_data(request):
    while True:
        line = msgutil.receive_message(request)
        print "received:", line
        line = str(int(line)*2)
        msgutil.send_message(request, line)
        if line == _GOODBYE_MESSAGE:
            return
def initialize_subscriber(request):
  line = msgutil.receive_message(request).encode('utf-8')
  try:
    msg = json.loads(line)
    sid = str(msg["subscribe"]["sid"])
    rid = str(msg["subscribe"]["rid"])
  except ValueError, e:
    msgutil.send_message(request, '%s' % json_message("message", str(e) + " " + line))
    return False
def web_socket_transfer_data(request):
	while True:
		line = msgutil.receive_message(request)
		if line == 'exit':
			return
		str = line.decode("string-escape")
		for c in str:
			msgutil._write(request, c)
			time.sleep(0.1)
示例#44
0
    def transfer_data(self, req):
        while True:
            try:
                line = receive_message(req)
            except TypeError, e: # connection closed
                self.log.debug("WS Error: %s" % e)
                return self.passive_closing_handshake(req)

            self.handle_message(line, req)
示例#45
0
def web_socket_transfer_data(request):
    expected_messages = ['Hello, world!', '', all_distinct_bytes()]

    for test_number, expected_message in enumerate(expected_messages):
        message = msgutil.receive_message(request)
        if type(message) == str and message == expected_message:
            msgutil.send_message(request, 'PASS: Message #%d.' % test_number)
        else:
            msgutil.send_message(request, 'FAIL: Message #%d: Received unexpected message: %r' % (test_number, message))
示例#46
0
    def transfer_data(self, req):
        while True:
            try:
                line = receive_message(req)
            except TypeError as e:  #: connection closed
                self.pyload.log.debug("WS Error: {0}".format(str(e)))
                return self.passive_closing_handshake(req)

            self.handle_message(line, req)
示例#47
0
    def test_receive_length_not_encoded_using_minimal_number_of_bytes(self):
        # Log warning on receiving bad payload length field that doesn't use
        # minimal number of bytes but continue processing.

        payload = 'a'
        # 1 byte can be represented without extended payload length field.
        request = _create_request(
            ('\x81\xff\x00\x00\x00\x00\x00\x00\x00\x01', payload))
        self.assertEqual(payload, msgutil.receive_message(request))
示例#48
0
    def transfer_data(self, req):
        while True:
            try:
                line = receive_message(req)
            except TypeError, e:  # connection closed
                self.log.debug("WS Error: %s" % e)
                return self.passive_closing_handshake(req)

            self.handle_message(line, req)
def web_socket_transfer_data(request):
    while True:
        line = msgutil.receive_message(request)
        if line == 'exit':
            return
        str = line.decode("string-escape")
        for c in str:
            msgutil._write(request, c)
            time.sleep(0.1)
示例#50
0
def web_socket_transfer_data(request):
    # Send three messages, and then wait for three messages.
    msgutil.send_message(request, '1')
    msgutil.send_message(request, '2')
    msgutil.send_message(request, '3')

    for expected in (u'1', u'2', u'3'):
        message = msgutil.receive_message(request)
        if type(message) != str or message != expected:
            raise handshake.AbortedByUserException('Abort the connection')
示例#51
0
    def test_receive_message_deflate(self):
        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED,
                                    -zlib.MAX_WBITS)

        compressed_hello = compress.compress(b'Hello')
        compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_hello = compressed_hello[:-4]
        data = b'\xc1%c' % (len(compressed_hello) | 0x80)
        data += _mask_hybi(compressed_hello)

        # Close frame
        data += b'\x88\x8a' + _mask_hybi(struct.pack('!H', 1000) + b'Good bye')

        extension = common.ExtensionParameter(
            common.PERMESSAGE_DEFLATE_EXTENSION)
        request = _create_request_from_rawdata(
            data, permessage_deflate_request=extension)
        self.assertEqual('Hello', msgutil.receive_message(request))

        self.assertEqual(None, msgutil.receive_message(request))
示例#52
0
def web_socket_transfer_data(request):
    # Make sure to receive a message from client before sending messages.
    client_message = msgutil.receive_message(request)
    messages_to_send = [
        b'Hello, world!', 'Привет, Мир!'.encode(), b'',
        all_distinct_bytes()
    ]
    for message in messages_to_send:
        # FIXME: Should use better API to send binary messages when pywebsocket supports it.
        header = stream.create_header(common.OPCODE_BINARY, len(message), 1, 0,
                                      0, 0, 0)
        request.connection.write(header + message)
示例#53
0
def web_socket_transfer_data(request):
    global connections
    connections[request] = True
    try:
        while True:
            msg = msgutil.receive_message(request)
            for ws in connections.keys():
                if ws != request:
                    msgutil.send_message(ws, msg)
    finally:
        # request is closed.
        del connections[request]
示例#54
0
def web_socket_transfer_data(request):
    data = getImage()
    while True:
        try:
            line = msgutil.receive_message(request).encode('utf-8')
            if line == _HEATBEAT:
                continue

            if (line != ''):
                msgutil.send_message(request, data.decode('utf-8'))
        except Exception:
            return
示例#55
0
    def test_receive_message_perframe_compression_frame(self):
        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED,
                                    -zlib.MAX_WBITS)

        data = ''

        compressed_hello = compress.compress('Hello')
        compressed_hello += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_hello = compressed_hello[:-4]
        data += '\xc1%c' % (len(compressed_hello) | 0x80)
        data += _mask_hybi(compressed_hello)

        compressed_websocket = compress.compress('WebSocket')
        compressed_websocket += compress.flush(zlib.Z_FINISH)
        compressed_websocket += '\x00'
        data += '\xc1%c' % (len(compressed_websocket) | 0x80)
        data += _mask_hybi(compressed_websocket)

        compress = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED,
                                    -zlib.MAX_WBITS)

        compressed_world = compress.compress('World')
        compressed_world += compress.flush(zlib.Z_SYNC_FLUSH)
        compressed_world = compressed_world[:-4]
        data += '\xc1%c' % (len(compressed_world) | 0x80)
        data += _mask_hybi(compressed_world)

        # Close frame
        data += '\x88\x8a' + _mask_hybi(struct.pack('!H', 1000) + 'Good bye')

        extension = common.ExtensionParameter(
            common.PERFRAME_COMPRESSION_EXTENSION)
        extension.add_parameter('method', 'deflate')
        request = _create_request_from_rawdata(
            data, perframe_compression_request=extension)
        self.assertEqual('Hello', msgutil.receive_message(request))
        self.assertEqual('WebSocket', msgutil.receive_message(request))
        self.assertEqual('World', msgutil.receive_message(request))

        self.assertEqual(None, msgutil.receive_message(request))
示例#56
0
def web_socket_transfer_data(request):
    w = AutoRuby()
    while True:
        try:
            line = msgutil.receive_message(request).encode('utf-8')
            if line == _HEATBEAT:
                continue

            if (line != ''):
                resp = w.run(line)
                msgutil.send_message(request, resp.decode('utf-8'))
        except Exception:
            return
示例#57
0
    def transfer_data(self, req):
        while True:

            if req.mode == Mode.STANDBY:
                try:
                    line = receive_message(req)
                except TypeError, e:  # connection closed
                    self.log.debug("WS Error: %s" % e)
                    return self.passive_closing_handshake(req)

                self.mode_standby(line, req)
            else:
                if self.mode_running(req):
                    return self.passive_closing_handshake(req)