Distibuted payload (message) to one connection
    :param conn: connection
    :param payload: payload(json dumpable)
    :return:
19891
def target_message(conn, payload):
    
    try:
        yield from conn.send(json.dumps(payload))
    except Exception as e:
        logger.debug('could not send', e)
615529
def HandleInvMessage(self, payload):
        

        if self.sync_mode != MODE_MAINTAIN:
            return

        inventory = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.InvPayload.InvPayload')
        if not inventory:
            return

        if inventory.Type == InventoryType.BlockInt:

            ok_hashes = []
            for hash in inventory.Hashes:
                hash = hash.encode('utf-8')
                if hash not in self.myblockrequests and hash not in BC.Default().BlockRequests:
                    ok_hashes.append(hash)
                    BC.Default().BlockRequests.add(hash)
                    self.myblockrequests.add(hash)
            if len(ok_hashes):
                message = Message("getdata", InvPayload(InventoryType.Block, ok_hashes))
                self.SendSerializedMessage(message)

        elif inventory.Type == InventoryType.TXInt:
            pass
        elif inventory.Type == InventoryType.ConsensusInt:
            pass
926732
def pack_into(self, buf, offset, write_payload):
    
    return self._get_framed(buf, offset, write_payload)
838103
def pipe_value(self, message):
        ''
        jmsg = json.dumps(message)
        self.send(jmsg)
987522
def event(self, name, payload=None, coalesce=True):
        
        return self.connection.call(
            'event',
            {'Name': name, 'Payload': payload, 'Coalesce': coalesce},
            expect_body=False)
77204
function (message, value, encoding) {
    message.payload = module.exports.encode(value, encoding)
  }
988950
def put(self, message):
        
        return self.connection.put('echo/string', data=dict(message=message))
1236672
def decode_network_packet(buf):
    
    off = 0
    blen = len(buf)

    while off < blen:
        ptype, plen = header.unpack_from(buf, off)

        if plen > blen - off:
            raise ValueError("Packet longer than amount of data in buffer")

        if ptype not in _decoders:
            raise ValueError("Message type %i not recognized" % ptype)

        yield ptype, _decoders[ptype](ptype, plen, buf[off:])
        off += plen
212001
def _reallysend(self, payload, token, expiration=None, priority=None, identifier=None):
        

        if not self.alive:
            raise ConnectionDeadException()
        if not self.useable:
            raise ConnectionDeadException()
        seq = self._nextSeq()
        if seq >= PushConnection.MAX_PUSHES_PER_CONNECTION:
            # IDs are 4 byte so rather than worry about wrapping IDs, just make a new connection
            # Note we don't close the connection because we want to wait to see if any errors arrive
            self._retire_connection()

        payload_str = json_for_payload(truncate(payload))
        items = ''
        items += self._apns_item(PushConnection.ITEM_DEVICE_TOKEN, token)
        items += self._apns_item(PushConnection.ITEM_PAYLOAD, payload_str)
        items += self._apns_item(PushConnection.ITEM_IDENTIFIER, seq)
        if expiration:
            items += self._apns_item(PushConnection.ITEM_EXPIRATION, expiration)
        if priority:
            items += self._apns_item(PushConnection.ITEM_PRIORITY, priority)

        apnsFrame = struct.pack("!BI", PushConnection.COMMAND_SENDPUSH, len(items)) + items

        try:
            written = 0
            while written < len(apnsFrame):
                written += self.sock.send(apnsFrame[written:])
        except:
            logger.exception("Caught exception sending push")
            raise
        self.sent[seq] = PushConnection.SentMessage(
            time.time(), token, payload, expiration, priority, identifier
        )
        self.last_push_sent = time.time()
781609
def __setup_connection(self):
            
        if self.payload != None and type(self.payload) is dict and 'settings' in self.payload:
            config.plugin_client_settings = self.payload['settings']
        config.offline = self.args.offline
        config.connection = PluginConnection(
            client=self.args.client or 'SUBLIME_TEXT_3',
            ui=self.args.ui_switch,
            args=self.args,
            params=self.payload,
            operation=self.operation,
            verbose=self.args.verbose)
        config.project = MavensMateProject(params=self.payload,ui=self.args.ui_switch)
        config.sfdc_client = config.project.sfdc_client
387303
def deliver_hook(self, instance, payload_override=None):
        
        payload = payload_override or self.serialize_hook(instance)
        if getattr(settings, 'HOOK_DELIVERER', None):
            deliverer = get_module(settings.HOOK_DELIVERER)
            deliverer(self.target, payload, instance=instance, hook=self)
        else:
            client.post(
                url=self.target,
                data=json.dumps(payload, cls=DjangoJSONEncoder),
                headers={'Content-Type': 'application/json'}
            )

        signals.hook_sent_event.send_robust(sender=self.__class__, payload=payload, instance=instance, hook=self)
        return None
1134788
async def _dhcp_handler(self):
        
        conn = self._connection
        ofdef = self._connection.openflowdef
        l3 = self._parent._gettableindex('l3input', self._connection.protocol.vhost)
        dhcp_packet_matcher = OpenflowAsyncMessageEvent.createMatcher(ofdef.OFPT_PACKET_IN, None, None, l3, 1,
                                                              self._connection, self._connection.connmark)
        # These tags are important options. They are sent first to make sure the client
        # correctly receive these options.
        required_tags = [d.OPTION_MESSAGE_TYPE, d.OPTION_SERVER_IDENTIFIER,
                         d.OPTION_NETMASK, d.OPTION_ROUTER,
                         d.OPTION_DNSSERVER, d.OPTION_BROADCAST, d.OPTION_MTU,
                         d.OPTION_LEASE_TIME, d.OPTION_T1, d.OPTION_T2]
        server_mac = mac_addr(self._parent.servermac)
        # IP fragment identifier
        trans_id = uint16.create(os.urandom(2))
        def set_options(payload, option_dict, provide_options, message_type, remove_lease = False):
            """
            Set DHCP options to output payload regarding the incoming request
            
            :param payload: output DHCP payload
            
            :param option_dict: incoming DHCP options in request
            
            :param provide_options: all DHCP options that are ready to sent to the client
            
            :param message_type: output DHCP message type
            
            :param remove_lease: remove all leases options. DHCPINFORM cannot contain
                                 leases options. See https://tools.ietf.org/html/rfc2131#section-3.4
            """
            message_type_opt = d.dhcp_option_message_type(value = message_type)
            if d.OPTION_REQUESTED_OPTIONS in option_dict:
                # First requested options, then required options, then others
                reqs = set(option_dict[d.OPTION_REQUESTED_OPTIONS].value)
                send_tags = [t for t in option_dict[d.OPTION_REQUESTED_OPTIONS].value
                             if t == d.OPTION_MESSAGE_TYPE or t in provide_options] \
                            + [t for t in required_tags
                               if (t in provide_options or t == d.OPTION_MESSAGE_TYPE) and t not in reqs] \
                            + [t for t in provide_options
                               if t not in reqs and t not in required_tags]
            else:
                # Required options, then others
                send_tags = [t for t in required_tags
                             if t in provide_options or t == d.OPTION_MESSAGE_TYPE] \
                            + [t for t in set(provide_options.keys()).difference(required_tags)]
            # If the client has sent an option for max message size, use it; or use the RFC required 576 bytes
            not_finished = d.build_options(
                                payload,
                                [message_type_opt if t == d.OPTION_MESSAGE_TYPE
                                  else provide_options[t] for t in send_tags
                                  if not remove_lease or (t != d.OPTION_LEASE_TIME and t != d.OPTION_T1 and t != OPTION_T2)],
                                max(min(option_dict[d.OPTION_MAX_MESSAGE_SIZE].value, 1400), 576)
                                if d.OPTION_MAX_MESSAGE_SIZE in option_dict
                                else 576)
        async def send_packet(pid, packet):
            """
            Send DHCP packet to specified port
            """
            await self.execute_commands(conn,
                            [ofdef.ofp_packet_out(
                                    buffer_id = ofdef.OFP_NO_BUFFER,
                                    in_port = ofdef.OFPP_CONTROLLER,
                                    actions = [ofdef.ofp_action_output(port = pid,
                                                                       max_len = ofdef.OFPCML_NO_BUFFER)],
                                    data = packet._tobytes()
                                )])
        while True:
            ev = await dhcp_packet_matcher
            msg = ev.message
            try:
                in_port = ofdef.ofp_port_no.create(ofdef.get_oxm(msg.match.oxm_fields, ofdef.OXM_OF_IN_PORT))
                if in_port not in self._dhcpentries:
                    # Not a DHCP-enabled port
                    continue
                port_mac, port_ip, server_ip, provide_options = self._dhcpentries[in_port]
                # Fragmented DHCP packets are not supported - this is allowed according
                # to RFC: server and clients are only needed to support at least 576 bytes
                # DHCP messages.
                l7_packet = ethernet_l7.create(msg.data)
                dhcp_packet = d.dhcp_payload.create(l7_packet.data)
                # We only process a DHCP request directly sent from the logical port
                if (dhcp_packet.op != d.BOOTREQUEST                            # A DHCP server packet
                        or dhcp_packet.hlen != 6 or dhcp_packet.htype != 1     # Hardware address not ethernet (48-bit)
                        or dhcp_packet.magic_cookie != d.BOOTP_MAGIC_COOKIE    # Magic cookie not match
                        or dhcp_packet.giaddr != 0):                           # A relayed DHCP message
                    raise ValueError('Unsupported DHCP packet')
                # Reassemble DHCP options
                options = d.reassemble_options(dhcp_packet)
                option_dict = dict((o.tag, o) for o in options)
                if d.OPTION_MESSAGE_TYPE not in option_dict:
                    raise ValueError('Message type not found')
                message_type = option_dict[d.OPTION_MESSAGE_TYPE].value
                is_nak = False
                if message_type == d.DHCPDISCOVER:
                    # A DHCPDISCOVER should get a DHCPOFFER response
                    if dhcp_packet.chaddr[:6].ljust(6, b'\x00') != mac_addr.tobytes(port_mac):
                        # MAC address not match, ignore this packet
                        continue
                    dhcp_reply = d.dhcp_payload(op = d.BOOTREPLY,
                                                htype = 1,
                                                hlen = 6,
                                                hops = 0,
                                                xid = dhcp_packet.xid,
                                                secs = 0,
                                                flags = dhcp_packet.flags,
                                                ciaddr = 0,
                                                yiaddr = port_ip,
                                                siaddr = 0,
                                                giaddr = dhcp_packet.giaddr,
                                                chaddr = dhcp_packet.chaddr,
                                                magic_cookie = d.BOOTP_MAGIC_COOKIE
                                                )
                    set_options(dhcp_reply, option_dict, provide_options, d.DHCPOFFER)
                elif message_type == d.DHCPREQUEST:
                    # A DHCPREQUEST should get a DHCPACK reply
                    if d.OPTION_SERVER_IDENTIFIER in option_dict and option_dict[d.OPTION_SERVER_IDENTIFIER].value != server_ip:
                        # Ignore packets to wrong address
                        continue
                    if dhcp_packet.chaddr[:6].ljust(6, b'\x00') != mac_addr.tobytes(port_mac) \
                            or (d.OPTION_REQUESTED_IP in option_dict and option_dict[d.OPTION_REQUESTED_IP].value != port_ip) \
                            or (dhcp_packet.ciaddr != 0 and dhcp_packet.ciaddr != port_ip):
                        # Requested MAC or IP not matched, send a NACK
                        dhcp_reply = d.dhcp_payload(op = d.BOOTREPLY,
                                                    htype = 1,
                                                    hlen = 6,
                                                    hops = 0,
                                                    xid = dhcp_packet.xid,
                                                    secs = 0,
                                                    flags = dhcp_packet.flags,
                                                    ciaddr = 0,
                                                    yiaddr = 0,
                                                    siaddr = 0,
                                                    giaddr = dhcp_packet.giaddr,
                                                    chaddr = dhcp_packet.chaddr,
                                                    magic_cookie = d.BOOTP_MAGIC_COOKIE
                                                    )
                        # Do not send more options in NACK
                        d.build_options(dhcp_reply, [d.dhcp_option_message_type(value = d.DHCPNAK),
                                                     d.dhcp_option_address(tag = d.OPTION_SERVER_IDENTIFIER,
                                                                           value = server_ip)], 576, 0)
                        is_nak = True
                    else:
                        dhcp_reply = d.dhcp_payload(op = d.BOOTREPLY,
                                                    htype = 1,
                                                    hlen = 6,
                                                    hops = 0,
                                                    xid = dhcp_packet.xid,
                                                    secs = 0,
                                                    flags = dhcp_packet.flags,
                                                    ciaddr = dhcp_packet.ciaddr,
                                                    yiaddr = port_ip,
                                                    siaddr = 0,
                                                    giaddr = dhcp_packet.giaddr,
                                                    chaddr = dhcp_packet.chaddr,
                                                    magic_cookie = d.BOOTP_MAGIC_COOKIE
                                                    )
                        set_options(dhcp_reply, option_dict, provide_options, d.DHCPACK)
                elif message_type == d.DHCPDECLINE:
                    # Address already in use?
                    self._logger.warning('DHCP client reports DHCPDECLINE, there should be some problems.'\
                                         ' Connection = %r(%016x), port = %d.',
                                         self._connection, self._connection.openflow_datapathid)
                elif message_type == d.DHCPRELEASE:
                    # Safe to ignore, we do not use a dynamic IP address pool
                    continue
                elif message_type == d.DHCPINFORM:
                    # Client setup IP addresses itself, but requesting more information
                    # DHCPINFORM reply cannot have lease options, and yiaddr = 0
                    dhcp_reply = d.dhcp_payload(op = d.BOOTREPLY,
                                                htype = 1,
                                                hlen = 6,
                                                hops = 0,
                                                xid = dhcp_packet.xid,
                                                secs = 0,
                                                flags = dhcp_packet.flags,
                                                ciaddr = dhcp_packet.ciaddr,
                                                yiaddr = 0,
                                                siaddr = 0,
                                                giaddr = dhcp_packet.giaddr,
                                                chaddr = dhcp_packet.chaddr,
                                                magic_cookie = d.BOOTP_MAGIC_COOKIE
                                                )
                    set_options(dhcp_reply, option_dict, provide_options, d.DHCPACK, True)
                trans_id = (trans_id + 1) & 0xffff
                if (dhcp_packet.flags & d.DHCPFLAG_BROADCAST) or is_nak:
                    # client request broadcast, or DHCPNAK
                    # RFC requires that DHCPNAK uses broadcast
                    dl_dst = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
                    ip_dst = 0xffffffff
                else:
                    dl_dst = l7_packet.dl_src
                    ip_dst = port_ip
                reply_packet = ip4_packet_l7((ip4_payload, ip4_udp_payload),
                                           dl_src = server_mac,
                                           dl_dst = dl_dst,
                                           identifier = trans_id,
                                           ttl = 128,
                                           ip_src = server_ip,
                                           ip_dst = ip_dst,
                                           sport = 67,
                                           dport = 68,
                                           data = dhcp_reply._tobytes()
                                           )
                # Send packet to the incoming port
                self.subroutine(send_packet(in_port, reply_packet), True)
            except Exception:
                self._logger.info('Invalid DHCP packet received: %r', msg.data, exc_info = True)
318036
def _pack(self, msg_type, payload):
        
        pb = payload.encode('utf-8')
        s = struct.pack('=II', len(pb), msg_type.value)
        return self.MAGIC.encode('utf-8') + s + pb
326975
async def send_rpc(self, conn_id, address, rpc_id, payload, timeout):
        

        self._ensure_connection(conn_id, True)
        connection_string = self._get_property(conn_id, "connection_string")

        msg = dict(address=address, rpc_id=rpc_id, payload=base64.b64encode(payload),
                   timeout=timeout, connection_string=connection_string)

        response = await self._send_command(OPERATIONS.SEND_RPC, msg, COMMANDS.SendRPCResponse,
                                            timeout=timeout)

        return unpack_rpc_response(response.get('status'), response.get('payload'),
                                   rpc_id=rpc_id, address=address)
572396
def _send(self, payload):

        '''
            
        '''

        if not self.connection:
            self._connect()

        # Send the payload, adding a newline to the end
        self.connection.send(payload + '\n')

        # Read 256 bytes off the socket and check the
        # status that returned.
        try:
            data = self.connection.recv(256)

        except socket.timeout, e:
            print 'Failed to read response in a timely manner to determine the status.'
            return False

        if data.split('\n')[1] == 'FAIL':
            print 'Failed to send payload: {payload}'.format(payload = payload)
            return False

        return True
1187212
def _read_payload(self, maxlen=None):
        

        client_address_str = "{}:{}".format(self.client_address[0], self.client_address[1])

        # check length
        read_len = self.headers.get('content-length', None)
        if read_len is None:
            log.error("No content-length given from {}".format(client_address_str))
            return None

        try:
            read_len = int(read_len)
        except:
            log.error("Invalid content-length")
            return None

        if maxlen is not None and read_len >= maxlen:
            log.error("Request from {} is too long ({} >= {})".format(client_address_str, read_len, maxlen))
            return None

        # get the payload
        request_str = self.rfile.read(read_len)
        return request_str
28003
def sendmess(self, msgtype, payload, flags=0, size=0, offset=0, timeout=0):
        

        # reuse last valid connection or create new
        conn = self.conn or self._new_connection()
        # invalidate last connection
        self.conn = None

        flags |= self.flags
        assert (flags & FLG_PERSISTENCE)
        ret, rflags, data = conn.req(
            msgtype, payload, flags, size, offset, timeout)
        if rflags & FLG_PERSISTENCE:
            # persistence granted, save connection object for reuse
            self.conn = conn
        else:
            # discard connection object
            conn.shutdown()

        return ret, data