Poll the websocket for a new packet.

        `Client.listen()` calls this.

        :param msg (string(byte array)): Optional. Parse the specified message
            instead of receiving a packet from the socket.
192821
def on_message(self, msg=None):
        
        if msg is None:
            try:
                msg = self.ws.recv()
            except Exception as e:
                self.subscriber.on_message_error(
                    'Error while receiving packet: %s' % str(e))
                self.disconnect()
                return False

        if not msg:
            self.subscriber.on_message_error('Empty message received')
            return False

        buf = BufferStruct(msg)
        opcode = buf.pop_uint8()
        try:
            packet_name = packet_s2c[opcode]
        except KeyError:
            self.subscriber.on_message_error('Unknown packet %s' % opcode)
            return False

        if not self.ingame and packet_name in ingame_packets:
            self.subscriber.on_ingame()
            self.ingame = True

        parser = getattr(self, 'parse_%s' % packet_name)
        try:
            parser(buf)
        except BufferUnderflowError as e:
            msg = 'Parsing %s packet failed: %s' % (packet_name, e.args[0])
            self.subscriber.on_message_error(msg)

        if len(buf.buffer) != 0:
            msg = 'Buffer not empty after parsing "%s" packet' % packet_name
            self.subscriber.on_message_error(msg)

        return packet_name
507815
async def receiver_handler(websocket):
    runner.addifnew(websocket)

    # The commented only works with python3-websockets 4.x
    '''
    
    '''

    while True:
        message = await websocket.recv()
        await consumer(websocket, message)
790808
def _accept(self, listen_socket):
        
        conn, addr = listen_socket.accept()
        connection = TelnetConnection(conn, addr, self.application, self, encoding=self.encoding)
        self.connections.add(connection)

        logger.info('New connection %r %r', *addr)
597253
function notifyWebSocket(message) {
	if (!webSocketServer || !message)
		return;
	
	// Send the message to all connection in the WebSocket server.
	for (var value in webSocketServer.conn) {
		var connection = webSocketServer.conn[value];
		if (connection)
			connection.send(message)
	}
}
507666
function listen(next) {

        listenSocket = dgram.createSocket({ type: 'udp4', reuseAddr: true });

        listenSocket.on('message', function(payload, rinfo) {
            var message = parseMessage(payload, rinfo);
            if (message) {
                if (message.id != id) {
                    if (message.status == "ONE") {
                        updateNodeList(message);
                    } else if (message.name != listenNameIdentifier && message.status == "NAMETAKEN") {
                        stop(function() {
                            //throw new Error('name already taken "' + name + '"');
                            self.emit("error", {cause: "Name already taken"});
                        });
                    }
                } else {
                    //self.emit('error', id + " already exists in network");
                    throw new Error(id + ' already exits in network');
                    stop();
                }
            }
        });

        listenSocket.bind(function(err) {
            var info = listenSocket.address();
            self.port = info.port;
            next(err);
        });

    }
553794
def send(self, message):
        
        try:
            self.ws.send(json.dumps(message))
        except websocket._exceptions.WebSocketConnectionClosedException:
            raise SelenolWebSocketClosedException()
24908
def receive_packet
      # Poll socket - is there data waiting?
      result = IO.select([@socket], [], [], SELECT_TIMEOUT)
      unless result.nil?
        # Yes - read in the packet
        packet = MQTT::Packet.read(@socket)
        handle_packet packet
      end
      keep_alive!
    # Pass exceptions up to parent thread
    rescue Exception => exp
      unless @socket.nil?
        @socket.close
        @socket = nil
      end
      Thread.current[:parent].raise(exp)
    end
709227
def handle_message(self, client_conn, msg):
        
        # log messages received so that no one else has to
        self._logger.debug('received: {0!s}'.format(msg))

        if msg.mtype == msg.REQUEST:
            return self.handle_request(client_conn, msg)
        elif msg.mtype == msg.INFORM:
            return self.handle_inform(client_conn, msg)
        elif msg.mtype == msg.REPLY:
            return self.handle_reply(client_conn, msg)
        else:
            reason = "Unexpected message type received by server ['%s']." \
                     % (msg,)
            client_conn.inform(self.create_log_inform("error", reason, "root"))
583447
def send(self, msg, timeout=None, tries=None):
        '''
        
        '''
        if not self.connected():
            yield self.connect()
        pack = salt.transport.frame.frame_msg_ipc(msg, raw_body=True)
        yield self.stream.write(pack)
1258558
def listen(self):
        
        import select
        while self.connected:
            r, w, e = select.select((self.ws.sock, ), (), ())
            if r:
                self.on_message()
            elif e:
                self.subscriber.on_sock_error(e)
        self.disconnect()
820687
public void receive(Message msg) {
        Request req=null;

        if(msg == null || msg.getLength() == 0)
            return;
        try {
            req=msg.getObject();

            String fqn=req.fqn;
            switch(req.type) {
                case Request.PUT:
                    if(req.key != null && req.value != null)
                        _put(fqn, req.key, req.value);
                    else
                        _put(fqn, req.data);
                    break;
                case Request.REMOVE:
                    if(req.key != null)
                        _remove(fqn, req.key);
                    else
                        _remove(fqn);
                    break;
                default:
                    if(log.isErrorEnabled()) log.error("type " + req.type + " unknown");
                    break;
            }
        }
        catch(Exception ex) {
            if(log.isErrorEnabled()) log.error("failed unmarshalling request: " + ex);
        }
    }
1181517
def on_message(self, message):
        
        message = ObjectDict(escape.json_decode(message))
        if message.command == 'hello':
            handshake = {
                'command': 'hello',
                'protocols': [
                    'http://livereload.com/protocols/official-7',
                ],
                'serverName': 'livereload-tornado',
            }
            self.send_message(handshake)

        if message.command == 'info' and 'url' in message:
            logger.info('Browser Connected: %s' % message.url)
            LiveReloadHandler.waiters.add(self)
383190
def _handleMessage(self, src_socket, msg):
        '''
        
        '''
        self._logger.debug('Message received: {!r}'.format(msg))

        # Check where the message came from and determine where it's going
        if src_socket is self._socket_a:
            src_name, src_host, src_port = 'A', self._host_a, self._port_a
            dst_name, dst_host, dst_port = 'B', self._host_b, self._port_b
            dst_socket = self._socket_b
        elif src_socket is self._socket_b:
            src_name, src_host, src_port = 'B', self._host_b, self._port_b
            dst_name, dst_host, dst_port = 'A', self._host_a, self._port_a
            dst_socket = self._socket_a
        else:
            self._logger.warning(
                'Message received from unknown socket! How is '
                'this possible?! Ignoring.')
            return False

        self._logger.debug(
            'Message received from host {:} ({!s}:{!s}), routing to host {:} '
            '({!s}:{!s})'
            .format(
                src_name, src_host, src_port,
                dst_name, dst_host, dst_port))

        # If the message is empty or non-existent then the connection has
        # closed
        if not msg or msg == '':
            self._logger.info(
                'Connection to host {:} closed'.format(src_name))
            return True

        # Apply middleware to the message if middleware exists
        if self._message_middleware is not None:
            msg = self._message_middleware(
                msg,
                src_name, src_host, src_port,
                dst_name, dst_host, dst_port)

        # Finally send the message
        dst_socket.send(msg)

        return False
692278
def receive_message(self, msg):
        
        if isinstance(msg, Resolution):
            return
        paxos = self.paxos_instance
        while msg:
            if isinstance(msg, Resolution):
                self.print_if_verbose("{} resolved value {}".format(self.network_uid, msg.value))
                break
            else:
                self.print_if_verbose("{} <- {} <- {}".format(self.network_uid, msg.__class__.__name__, msg.from_uid))
                msg = paxos.receive(msg)
                # Todo: Make it optional not to announce resolution (without which it's hard to see final value).
                do_announce_resolution = True
                if msg and (do_announce_resolution or not isinstance(msg, Resolution)):
                    self.announce(msg)

        self.setattrs_from_paxos(paxos)
892627
def receive(self):
        
        if self._closed:
            raise WebSocketError("Connection is already closed")
        try:
            return self.read_message()
        except UnicodeError as e:
            logger.info('websocket.receive: UnicodeError {}'.format(e))
            self.close(1007)
        except WebSocketError as e:
            logger.info('websocket.receive: WebSocketError {}'.format(e))
            self.close(1002)
        except Exception as e:
            logger.info('websocket.receive: Unknown error {}'.format(e))
            raise e
532944
async def respond(self, *args, **kwargs):
        
        return await self._client.send_message(
            await self.get_input_chat(), *args, **kwargs)
1213786
def run(self, *args):
        
        del args

        arec = AddressReceiver(max_age=self._max_age,
                               multicast_enabled=self._multicast_enabled)
        arec.start()
        port = PORT

        try:
            with nslock:
                self.listener = get_context().socket(REP)
                self.listener.bind("tcp://*:" + str(port))
                logger.debug('Listening on port %s', str(port))
                poller = Poller()
                poller.register(self.listener, POLLIN)
            while self.loop:
                with nslock:
                    socks = dict(poller.poll(1000))
                    if socks:
                        if socks.get(self.listener) == POLLIN:
                            msg = self.listener.recv_string()
                    else:
                        continue
                    logger.debug("Replying to request: " + str(msg))
                    msg = Message.decode(msg)
                    self.listener.send_unicode(six.text_type(get_active_address(
                        msg.data["service"], arec)))
        except KeyboardInterrupt:
            # Needed to stop the nameserver.
            pass
        finally:
            arec.stop()
            self.stop()