Function to send messages
        
        Parameters
        ----------
        connection: socket or connection
        data: data that can be serialized to json
971733
def send_msg(self, connection, data):
        
        # serialize as JSON
        msg = json.dumps(data)
        # Prefix each message with a 4-byte length (network byte order)
        msg = struct.pack('>I', len(msg)).decode() + msg
        connection.sendall(msg.encode())
        return
1255858
def send(self):
        
        buf_sz = 500
        to_send = {}

        for mn in self.data.iterkeys():
            while len(self.data[mn]) > 0:
                l = len(to_send)
                if l < buf_sz:
                    to_send.setdefault(mn, [])
                    to_send[mn].append(self.data[mn].pop())
                else:
                    try:
                        self._send(to_send)
                        to_send = {}
                        to_send.setdefault(mn, [])
                        to_send[mn].append(self.data[mn].pop())
                    except socket.error:
                        self.logger.error('Error sending to carbon, trying to reconnect.')
                        self.sock = self._connect()

                        # we failed to send, so put it back in the stack and try later
                        for ent in to_send:
                            self.data[ent[0]].append(ent[1])

        try:
            self._send(to_send)
        except socket.error:
            self.logger.error('Error sending to carbon, trying to reconnect.')
            self.sock = self._connect()

        # we failed to send, so put it back in the stack and try later
        for ent in to_send:
            self.data[ent[0]].append(ent[1])
1175886
def _send(self, data):
        
        # check link
        if self.__sock is None:
            self.__debug_msg('call _send on close socket')
            return None
        # send
        data_l = len(data)
        try:
            send_l = self.__sock.send(data)
        except socket.error:
            send_l = None
        # handle send error
        if (send_l is None) or (send_l != data_l):
            self.__last_error = const.MB_SEND_ERR
            self.__debug_msg('_send error')
            self.close()
            return None
        else:
            return send_l
1374611
async def send(self, data: Union[bytes, str], final: bool = True):
        
        MsgType = TextMessage if isinstance(data, str) else BytesMessage
        data = MsgType(data=data, message_finished=final)
        data = self._connection.send(event=data)
        await self._sock.send_all(data)
506895
def send(self, *args):
        
        msg = " ".join(a.nick if isinstance(a, User) else str(a) for a in args)
        if "\n" in msg:
            raise ValueError("Cannot send() a newline. Args: %s" % repr(args))
        _log.debug("%s <-- %s", self.server.host, msg)
        self.socket.send(msg + "\r\n")
21916
def run(connection)
      connection.public_send(verb, path) do |request|
        request.params = params
        request.headers[:content_type] = Command::JSON_CONTENT_TYPE
        request.body = MultiJson.dump(body)
      end
    end
376390
def send_message(self, msg, connection_id=None):
        
        zmq_identity = None
        if connection_id is not None and self._connections is not None:
            if connection_id in self._connections:
                connection_info = self._connections.get(connection_id)
                if connection_info.connection_type == \
                        ConnectionType.ZMQ_IDENTITY:
                    zmq_identity = connection_info.connection
            else:
                LOGGER.debug("Can't send to %s, not in self._connections",
                             connection_id)

        self._ready.wait()

        if zmq_identity is None:
            message_bundle = [msg.SerializeToString()]
        else:
            message_bundle = [bytes(zmq_identity),
                              msg.SerializeToString()]

        try:
            asyncio.run_coroutine_threadsafe(
                self._send_message_frame(message_bundle),
                self._event_loop)
        except RuntimeError:
            # run_coroutine_threadsafe will throw a RuntimeError if
            # the eventloop is closed. This occurs on shutdown.
            pass
1061056
def send_message(self, data):
        
        opcode = BINARY
        if _check_unicode(data):
            opcode = TEXT

        self._send_message(False, opcode, data)
485341
def _send_packet(self, data):
        
        if self._closed:
            return

        data = json.dumps(data)

        def send():
            try:
                yield From(self.pipe_connection.write(data))
            except BrokenPipeError:
                self.detach_and_close()
        ensure_future(send())
575510
def send_message(
        self, request: str, response_expected: bool, **kwargs: Any
    ) -> Response:
        
        self.socket.send_string(request)
        return Response(self.socket.recv().decode())
261545
def send(self, message):
        
        self.logger.debug('Send message: {}'.format(message))

        if self.state == 'pending' or self.state == 'connection_pending':
            self.logger.info('Connection not established. Add message to queue.')
            self.message_queue.append(message)
            return
        elif self.state == 'unsubscribed' or self.state == 'rejected':
            self.logger.warning('Not subscribed! Message discarded.')
            return

        data = {
            'command': 'message',
            'identifier': self._identifier_string(),
            'data': message.raw_message()
        }

        self.connection.send(data)
976637
def message(self, data, kind="info"):
        """"""
        message = pd.io.json.dumps({'kind': kind, 'data': data})
        print("Sent {0} bytes.".format(len(message)))
        self.write_message(message)
543894
def socket_reader(connection: socket, buffer_size: int = 1024):
    
    while connection is not None:
        try:
            buffer = connection.recv(buffer_size)
            # no output
            if not len(buffer):
                raise ConnectionAbortedError
        except ConnectionAbortedError:
            # socket closed
            print('connection aborted')
            connection.close()
            yield None
        except OSError:
            # still operate connection after it was closed
            print('socket closed')
            connection.close()
            yield None
        else:
            yield buffer
863190
def send(self, data):
        

        if self.sock is None:
            if self.auto_open:
                self.connect()
            else:
                raise NotConnected()

        if self.debuglevel > 0:
            print("send:", repr(data))
        blocksize = 8192
        # Python 2.7 array objects have a read method which is incompatible
        # with the 2-arg calling syntax below.
        if hasattr(data, "read") and not isinstance(data, array):
            if self.debuglevel > 0:
                print("sendIng a read()able")
            encode = False
            try:
                mode = data.mode
            except AttributeError:
                # io.BytesIO and other file-like objects don't have a `mode`
                # attribute.
                pass
            else:
                if "b" not in mode:
                    encode = True
                    if self.debuglevel > 0:
                        print("encoding file using iso-8859-1")
            while 1:
                datablock = data.read(blocksize)
                if not datablock:
                    break
                if encode:
                    datablock = datablock.encode("iso-8859-1")
                self.sock.sendall(datablock)
            return
        try:
            self.sock.sendall(data)
        except TypeError:
            if isinstance(data, collections.Iterable):
                for d in data:
                    self.sock.sendall(d)
            else:
                raise TypeError("data should be a bytes-like object "
                                "or an iterable, got %r" % type(data))
224085
def on_connect(self, connection):
        ""
        self._stream = connection._reader
        self._buffer = SocketBuffer(self._stream, self._read_size)
        if connection.decode_responses:
            self.encoding = connection.encoding
630661
function Message(connection) {
  // Inherit from event emitter
  var that = this;
  EventEmitter.call(this);

  // Save the connection
  this.connection = connection;

  // If there is a body already, don't buffer
  if (connection.body) {
    that.body = connection.body;
    async.setImmediate(function () {
      that.emit('loaded');
    });
    return;
  }

  // Buffer the content of the connecftion
  connection.pipe(concat(function handleBuffer (buff) {
    // Save the body and emit a `loaded` event
    // DEV: The delay is so `async.waterfall` still operates when we enter it
    that.body = buff.length ? buff : '';
    async.setImmediate(function () {
      that.emit('loaded');
    });
  }));
}
553794
def send(self, message):
        
        try:
            self.ws.send(json.dumps(message))
        except websocket._exceptions.WebSocketConnectionClosedException:
            raise SelenolWebSocketClosedException()