Send a raw BSON message or raise ConnectionFailure.

        If a network exception is raised, the socket is closed.
359942
def send_message(self, message, max_doc_size):
        
        if (self.max_bson_size is not None
                and max_doc_size > self.max_bson_size):
            raise DocumentTooLarge(
                "BSON document too large (%d bytes) - the connected server "
                "supports BSON document sizes up to %d bytes." %
                (max_doc_size, self.max_bson_size))

        try:
            self.sock.sendall(message)
        except BaseException as error:
            self._raise_connection_failure(error)
86696
async def _handle_exception(self, e, sock):
        
        if isinstance(e, (RemoteProtocolError, AssertionError)):
            await sock.close()
            raise BadHttpResponse('Invalid HTTP response from server.') from e

        if isinstance(e, Exception):
            await sock.close()
            raise e
363698
def _client_connection(self, conn, addr):
        '''
        
        '''
        log.debug('Established connection with %s:%d', addr[0], addr[1])
        conn.settimeout(self.socket_timeout)
        try:
            while self.__up:
                msg = conn.recv(self.buffer_size)
                if not msg:
                    # log.debug('Received empty message from %s', addr)
                    # disabled ^ as it was too noisy
                    continue
                log.debug('[%s] Received %s from %s. Adding in the queue', time.time(), msg, addr)
                self.buffer.put((msg, '{}:{}'.format(addr[0], addr[1])))
        except socket.timeout:
            if not self.__up:
                return
            log.debug('Connection %s:%d timed out', addr[1], addr[0])
            raise ListenerException('Connection %s:%d timed out' % addr)
        finally:
            log.debug('Closing connection with %s', addr)
            conn.close()
279795
def wait(self):
        
        if self.error:
            raise self.error
        if not self.running:
            raise ValueError("Unable to send until client has been started.")
        try:
            self._handler.wait()
        except (errors.TokenExpired, errors.AuthenticationException):
            log.info("Sender disconnected due to token error. Attempting reconnect.")
            self.reconnect()
        except (errors.LinkDetach, errors.ConnectionClose) as shutdown:
            if shutdown.action.retry and self.auto_reconnect:
                log.info("Sender detached. Attempting reconnect.")
                self.reconnect()
            else:
                log.info("Sender detached. Shutting down.")
                error = EventHubError(str(shutdown), shutdown)
                self.close(exception=error)
                raise error
        except errors.MessageHandlerError as shutdown:
            if self.auto_reconnect:
                log.info("Sender detached. Attempting reconnect.")
                self.reconnect()
            else:
                log.info("Sender detached. Shutting down.")
                error = EventHubError(str(shutdown), shutdown)
                self.close(exception=error)
                raise error
        except Exception as e:
            log.info("Unexpected error occurred (%r).", e)
            raise EventHubError("Send failed: {}".format(e))
490125
function sendConnectFailed(wsConn) {
    var message = {
      type:  "response",
      name:  "connect",
      from:  "server",
      error: "invalid connect message"
    }

    wsConn.sendUTF(JSON.stringify(message))
    wsConn.close(1000, message.error)
    cleanUp()
  }
76175
def send_raw(self, string):
        
        log.debug('RAW: {}'.format(string))
        if self.transport is None:
            raise ServerNotConnectedError("Not connected.")

        self.transport.write(self._prep_message(string))
138270
synchronized void connectionFailed(Throwable t) {
        if (!isConnected()) {
            //another thread already disconnected this connector, so return
            return;
        }

        if (logger.isLoggable(Level.FINER)) {
            logger.logp(Level.FINER, logger.getName(), "connectionFailed", "Connection failed: " + RESTClientMessagesUtil.getObjID(this));
        }

        disconnect();

        if (notificationRegistry != null) {
            notificationRegistry.close();
        }

        //Emit the notification
        connector.connectionFailed(t);
    }
904495
private void checkNotClosed() throws SIConnectionUnavailableException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "checkNotClosed");

        //Synchronize on the closed object to prevent it being changed while we check it.
        synchronized (this)
        {
            if (_closed)
            {
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                    SibTr.exit(tc, "checkNotClosed", "Connection Closed exception");
                SIMPConnectionUnavailableException e = new SIMPConnectionUnavailableException(
                                nls_cwsik.getFormattedMessage(
                                                              "DELIVERY_ERROR_SIRC_22", // OBJECT_CLOSED_ERROR_CWSIP0091
                                                              new Object[] { _messageProcessor.getMessagingEngineName() },
                                                              null));

                e.setExceptionReason(SIRCConstants.SIRC0022_OBJECT_CLOSED_ERROR);
                e.setExceptionInserts(new String[] { _messageProcessor.getMessagingEngineName() });

                throw e;
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "checkNotClosed");
    }
799141
def _send_raw(self, command):
        
        try:
            self._socket.send(bytearray(command))
            self._sn = (self._sn + 1) % 256
            return True
        except (socket.error, socket.timeout):
            # We can get a socket.error or timeout exception if the bridge is disconnected,
            # but we are still sending data. In that case, return False to indicate that data is not sent.
            return False
580714
def maybe_sendraw(self, host_port: Tuple[int, int], messagedata: bytes):
        

        # Don't sleep if timeout is zero, otherwise a context-switch is done
        # and the message is delayed, increasing its latency
        sleep_timeout = self.throttle_policy.consume(1)
        if sleep_timeout:
            gevent.sleep(sleep_timeout)

        # Check the udp socket is still available before trying to send the
        # message. There must be *no context-switches after this test*.
        if hasattr(self.server, 'socket'):
            self.server.sendto(
                messagedata,
                host_port,
            )
1324525
private void sendSOCreationFailed(RTMPConnection conn, SharedObjectMessage message) {
        log.debug("sendSOCreationFailed - message: {} conn: {}", message, conn);
        // reset the object so we can re-use it
        message.reset();
        // add the error event
        message.addEvent(new SharedObjectEvent(ISharedObjectEvent.Type.CLIENT_STATUS, "error", SO_CREATION_FAILED));
        if (conn.isChannelUsed(3)) {
            // XXX Paul: I dont like this direct write stuff, need to move to event-based
            conn.getChannel(3).write(message);
        } else {
            log.warn("Channel is not in-use and cannot handle SO event: {}", message, new Exception("SO event handling failure"));
            // XXX Paul: I dont like this direct write stuff, need to move to event-based
            conn.getChannel(3).write(message);
        }
    }
83747
def connection_lost(self, exc):
        ''''''
        # Work around uvloop bug; see https://github.com/MagicStack/uvloop/issues/246
        if self.transport:
            self.transport = None
            self.closed_event.set()
            # Release waiting tasks
            self._can_send.set()
            # Cancelling directly leads to self-cancellation problems for member
            # functions await-ing self.close()
            self.loop.call_soon(self._task.cancel)
1350755
def send_message(self, message):
        
        if not isinstance(message, txdbus.DbusMessage):
            raise TypeError('message: expecting DbusMessage instance (got {!r})',
                                type(message).__name__)
        self._name_acquired.wait()
        if self._error:
            raise compat.saved_exc(self._error)
        elif self._transport is None:
            raise DbusError('not connected')
        self._writer.write(message.rawMessage)
714138
def send(self, message) :
        ""
        if not isinstance(message, Message) :
            raise TypeError("message must be a Message")
        #end if
        serial = ct.c_uint()
        if not dbus.dbus_connection_send(self._dbobj, message._dbobj, ct.byref(serial)) :
            raise CallFailed("dbus_connection_send")
        #end if
        return \
            serial.value
275157
def connectionLost(self, reason):
        
        AMP.connectionLost(self, reason)
        if self.logout is not None:
            self.logout()
            self.boxReceiver = self.logout = None
1264462
def fanout_message(connections, payload):
    
    for conn in connections:
        try:
            yield from conn.send(json.dumps(payload))
        except Exception as e:
            logger.debug('could not send', e)
1295333
@Override
  public void onFailure(WebSocket webSocket, Throwable t, Response response) {
    socketOpen = false;
    if (t instanceof Exception) {
      callback.onError((Exception) t);
    } else {
      callback.onError(new Exception(t));
    }
  }