Beispiel #1
0
class EchoClient(object):
    """WebSocket echo client."""

    def __init__(self, options):
        self._options = options
        self._socket = None

        self._logger = util.get_class_logger(self)

    def run(self):
        """Run the client.

        Shake hands and then repeat sending message and receiving its echo.
        """

        self._socket = socket.socket()
        self._socket.settimeout(self._options.socket_timeout)
        try:
            self._socket.connect((self._options.server_host,
                                  self._options.server_port))
            if self._options.use_tls:
                self._socket = _TLSSocket(
                    self._socket,
                    self._options.tls_module,
                    self._options.tls_version,
                    self._options.disable_tls_compression)

            version = self._options.protocol_version

            if (version == _PROTOCOL_VERSION_HYBI08 or
                version == _PROTOCOL_VERSION_HYBI13):
                self._handshake = ClientHandshakeProcessor(
                    self._socket, self._options)
            elif version == _PROTOCOL_VERSION_HYBI00:
                self._handshake = ClientHandshakeProcessorHybi00(
                    self._socket, self._options)
            else:
                raise ValueError(
                    'Invalid --protocol-version flag: %r' % version)

            self._handshake.handshake()

            self._logger.info('Connection established')

            request = ClientRequest(self._socket)

            version_map = {
                _PROTOCOL_VERSION_HYBI08: common.VERSION_HYBI08,
                _PROTOCOL_VERSION_HYBI13: common.VERSION_HYBI13,
                _PROTOCOL_VERSION_HYBI00: common.VERSION_HYBI00}
            request.ws_version = version_map[version]

            if (version == _PROTOCOL_VERSION_HYBI08 or
                version == _PROTOCOL_VERSION_HYBI13):
                stream_option = StreamOptions()
                stream_option.mask_send = True
                stream_option.unmask_receive = False

                if self._options.deflate_frame is not False:
                    processor = self._options.deflate_frame
                    processor.setup_stream_options(stream_option)

                if self._options.use_permessage_deflate is not False:
                    framer = self._options.use_permessage_deflate
                    framer.setup_stream_options(stream_option)

                self._stream = Stream(request, stream_option)
            elif version == _PROTOCOL_VERSION_HYBI00:
                self._stream = StreamHixie75(request, True)

            for line in self._options.message.split(','):
                self._stream.send_message(line)
                if self._options.verbose:
                    print('Send: %s' % line)
                try:
                    received = self._stream.receive_message()

                    if self._options.verbose:
                        print('Recv: %s' % received)
                except Exception, e:
                    if self._options.verbose:
                        print('Error: %s' % e)
                    raise

            self._do_closing_handshake()
        finally:
Beispiel #2
0
# send a sequence of messages to the server, hardcoded for now
msg_list = ['SET auth t=kiwi p=', 'SET zoom=%d start=%d'%(zoom,offset),\
'SET maxdb=0 mindb=-100', 'SET wf_speed=4', 'SET wf_comp=0']
for msg in msg_list:
    mystream.send_message(msg)
print "Starting to retrieve waterfall data..."
# number of samples to draw from server
length = options['length']
# create a numpy array to contain the waterfall data
wf_data = np.zeros((length, bins))
binary_wf_list = []
time = 0
while time<length:
    # receive one msg from server
    tmp = mystream.receive_message()
    if "W/F" in tmp: # this is one waterfall line
        tmp = tmp[16:] # remove some header from each msg
        if options['verbosity']:
            print time,
        spectrum = np.array(struct.unpack('%dB'%len(tmp), tmp) ) # convert from binary data to uint8
        if filename:
            binary_wf_list.append(tmp) # append binary data to be saved to file
        wf_data[time, :] = spectrum-255 # mirror dBs
        time += 1
    else: # this is chatter between client and server
        #print tmp
        pass

try:
    mystream.close_connection()
Beispiel #3
0
class Connection(object):
	"""WebSocket echo client."""

	def __init__(self, configFile):
		print "connection init"
		self.configFile = configFile
		self.dictionary=dict()
		with open(self.configFile, 'r') as f:
			for singleLine in f:
				singleLine = singleLine.replace('\n','')
				splitedLine = singleLine.split('=')
				self.dictionary[splitedLine[0]] = splitedLine[1]
		print self.dictionary
		logging.basicConfig(level=logging.getLevelName(self.dictionary.get('log_level').upper()))
		self._socket = None
		self.received = Queue()
		self.toSend = Queue()
		self._logger = util.get_class_logger(self)

	def connect(self):

		self._socket = socket.socket()
		self._socket.settimeout(int(self.dictionary.get('socket_timeout')))
		try:
			self._socket.connect((self.dictionary.get('server_host'),
			                      int(self.dictionary.get('server_port'))))
			if self.dictionary.get('use_tls') == 'True':
				self._socket = _TLSSocket(self._socket)

			version = self.dictionary.get('protocol_version')

			self._handshake = ClientHandshakeProcessor(
				self._socket, self.dictionary)

			self._handshake.handshake()

			self._logger.info('Connection established')

			request = ClientRequest(self._socket)

			version_map = {
				_PROTOCOL_VERSION_HYBI13: common.VERSION_HYBI13}
			request.ws_version = version_map[version]

			stream_option = StreamOptions()
			stream_option.mask_send = True
			stream_option.unmask_receive = False

			if self.dictionary.get('deflate_stream') == 'True':
				stream_option.deflate_stream = True

			if self.dictionary.get('deflate_frame') == 'True':
				processor = True
				processor.setup_stream_options(stream_option)

			self._stream = Stream(request, stream_option)
			listen = ListenSocket(self, self.received)
			write = WriteSocket(self, self.toSend)
			listen.start()
			write.start()
		finally:
			print "po powitaniu, serwer oczekuje na dane"

	def send(self, message):
		for line in message.split(','):
			self.toSend.put(line)
#			self._stream.send_message(line)
			print 'Send: %s' % line

	def get_message(self):
			return self.received.get(True)

	def _do_closing_handshake(self):
		"""Perform closing handshake using the specified closing frame."""

		if self.dictionary.get('message').split(',')[-1] == _GOODBYE_MESSAGE:
			# requested server initiated closing handshake, so
			# expecting closing handshake message from server.
			self._logger.info('Wait for server-initiated closing handshake')
			message = self._stream.receive_message()
			if message is None:
				return
		self._stream.close_connection()
Beispiel #4
0
class EchoClient(object):
    """WebSocket echo client."""
    def __init__(self, options):
        self._options = options
        self._socket = None

        self._logger = util.get_class_logger(self)

    def run(self):
        """Run the client.

        Shake hands and then repeat sending message and receiving its echo.
        """

        self._socket = socket.socket()
        self._socket.settimeout(self._options.socket_timeout)
        try:
            self._socket.connect(
                (self._options.server_host, self._options.server_port))
            if self._options.use_tls:
                self._socket = _TLSSocket(self._socket)

            self._handshake = ClientHandshakeProcessor(self._socket,
                                                       self._options)

            self._handshake.handshake()

            self._logger.info('Connection established')

            request = ClientRequest(self._socket)

            stream_option = StreamOptions()
            stream_option.mask_send = True
            stream_option.unmask_receive = False

            if self._options.use_permessage_deflate is not False:
                framer = self._options.use_permessage_deflate
                framer.setup_stream_options(stream_option)

            self._stream = Stream(request, stream_option)

            for line in self._options.message.split(','):
                self._stream.send_message(line)
                if self._options.verbose:
                    print('Send: %s' % line)
                try:
                    received = self._stream.receive_message()

                    if self._options.verbose:
                        print('Recv: %s' % received)
                except Exception as e:
                    if self._options.verbose:
                        print('Error: %s' % e)
                    raise

            self._do_closing_handshake()
        finally:
            self._socket.close()

    def _do_closing_handshake(self):
        """Perform closing handshake using the specified closing frame."""

        if self._options.message.split(',')[-1] == _GOODBYE_MESSAGE:
            # requested server initiated closing handshake, so
            # expecting closing handshake message from server.
            self._logger.info('Wait for server-initiated closing handshake')
            message = self._stream.receive_message()
            if message is None:
                print('Recv close')
                print('Send ack')
                self._logger.info('Received closing handshake and sent ack')
                return
        print('Send close')
        self._stream.close_connection()
        self._logger.info('Sent closing handshake')
        print('Recv ack')
        self._logger.info('Received ack')