Called when a datagram is received over a stream.
490564
def ApplicationDatagram(self, app, stream, text):
        """"""

        # we should only proceed if we are in UDP mode
        if stype != socket.SOCK_DGRAM:
            return

        # decode the data
        data = base64.decodestring(text)

        # open an UDP socket
        sock = socket.socket(type=stype)

        # send the data
        try:
            sock.sendto(data, addr)
        except socket.error, e:
            print 'error: %s' % e
42898
def sendDAT(self):
        """"""
        finished = False
        blocknumber = self.context.next_block
        # Test hook
        if DELAY_BLOCK and DELAY_BLOCK == blocknumber:
            import time
            log.debug("Deliberately delaying 10 seconds...")
            time.sleep(10)
        dat = None
        blksize = self.context.getBlocksize()
        buffer = self.context.fileobj.read(blksize)
        log.debug("Read %d bytes into buffer", len(buffer))
        if len(buffer) < blksize:
            log.info("Reached EOF on file %s"
                % self.context.file_to_transfer)
            finished = True
        dat = TftpPacketDAT()
        dat.data = buffer
        dat.blocknumber = blocknumber
        self.context.metrics.bytes += len(dat.data)
        log.debug("Sending DAT packet %d", dat.blocknumber)
        self.context.sock.sendto(dat.encode().buffer,
                                 (self.context.host, self.context.tidport))
        if self.context.packethook:
            self.context.packethook(dat)
        self.context.last_pkt = dat
        return finished
304365
def _stream_send_and_receive(self, _socket, message, *args, **kwargs):
        """"""
        data = BytesIO()

        _socket_fd = _socket.makefile(mode='rwb', encoding='utf-8')
        _socket_fd.write(message.encode('utf-8'))
        _socket_fd.flush()

        for received in _socket_fd:
            data.write(received)
        data.seek(0)

        _socket_fd.close()
        return data
272603
public static void runReadLoop(InputStream stream, StreamConnection connection) throws Exception {
        ByteBuffer dbuf = ByteBuffer.allocateDirect(Math.min(Math.max(connection.getMaxMessageSize(), BUFFER_SIZE_LOWER_BOUND), BUFFER_SIZE_UPPER_BOUND));
        byte[] readBuff = new byte[dbuf.capacity()];
        while (true) {
            // TODO Kill the message duplication here
            checkState(dbuf.remaining() > 0 && dbuf.remaining() <= readBuff.length);
            int read = stream.read(readBuff, 0, Math.max(1, Math.min(dbuf.remaining(), stream.available())));
            if (read == -1)
                return;
            dbuf.put(readBuff, 0, read);
            // "flip" the buffer - setting the limit to the current position and setting position to 0
            dbuf.flip();
            // Use connection.receiveBytes's return value as a double-check that it stopped reading at the right
            // location
            int bytesConsumed = connection.receiveBytes(dbuf);
            checkState(dbuf.position() == bytesConsumed);
            // Now drop the bytes which were read by compacting dbuf (resetting limit and keeping relative
            // position)
            dbuf.compact();
        }
    }
492310
async def _receive_data_chunk(self, chunk):
        
        self._sack_needed = True

        # mark as received
        if self._mark_received(chunk.tsn):
            return

        # find stream
        inbound_stream = self._get_inbound_stream(chunk.stream_id)

        # defragment data
        inbound_stream.add_chunk(chunk)
        self._advertised_rwnd -= len(chunk.user_data)
        for message in inbound_stream.pop_messages():
            self._advertised_rwnd += len(message[2])
            await self._receive(*message)
1176275
def send_datagram(self, message):
        
        if not self.stopped.isSet():
            host, port = message.destination
            logger.debug("send_datagram - " + str(message))
            serializer = Serializer()

            message = serializer.serialize(message)

            self._socket.sendto(message, (host, port))
25089
private void handleIncomingPacket(DatagramPacket packet) {
    SsdpResponse response = new ResponseParser().parse(packet);
    if (response == null) {
      // Unknown to protocol
      return;
    }
    if (response.getType().equals(SsdpResponse.Type.DISCOVERY_RESPONSE)) {
      handleDiscoveryResponse(response);
    } else if (response.getType().equals(SsdpResponse.Type.PRESENCE_ANNOUNCEMENT)) {
      handlePresenceAnnouncement(response);
    }
  }
36475
function (dataChannel, info, event) {
        if (event.data instanceof ArrayBuffer) {
          self.dispatchEvent('onReceived', {
            'channelLabel': info.label,
            'buffer': event.data
          });
        } else if (event.data instanceof Blob) {
          self.dispatchEvent('onReceived', {
            'channelLabel': info.label,
            'binary': event.data
          });
        } else if (typeof (event.data) === 'string') {
          self.dispatchEvent('onReceived', {
            'channelLabel': info.label,
            'text': event.data
          });
        }
      }
342792
private boolean transfer(long total,
                             GlobusInputStream in,
                             GlobusOutputStream out)
        throws IOException {

        byte [] buffer       = new byte[bufferSize];
        int bytes            = 0;
        long totalBytes      = total;
        long transferedBytes = 0;

        if (total == -1) {
            while( (bytes = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytes);
                out.flush();

                if (listeners != null) {
                    transferedBytes += bytes;
                    fireUrlTransferProgressEvent(totalBytes,
                                                 transferedBytes);
                }
                if (isCanceled()) return false;
            }
        } else {
            while ( total != 0 ) {

                bytes = bufferSize;
                if (total < bufferSize) bytes = (int)total;

                bytes = in.read(buffer);
                out.write(buffer, 0, bytes);
                out.flush();
                total -= bytes;

                if (listeners != null) {
                    transferedBytes += bytes;
                    fireUrlTransferProgressEvent(totalBytes,
                                                 transferedBytes);
                }
                if (isCanceled()) return false;
            }
        }

        return true;
    }
452550
private void handleSendDataRequest(SerialMessage incomingMessage) {
		logger.trace("Handle Message Send Data Request");
		
		int callbackId = incomingMessage.getMessagePayloadByte(0);
		TransmissionState status = TransmissionState.getTransmissionState(incomingMessage.getMessagePayloadByte(1));
		SerialMessage originalMessage = this.lastSentMessage;
		
		if (status == null) {
			logger.warn("Transmission state not found, ignoring.");
			return;
		}

		logger.debug("CallBack ID = {}", callbackId);
		logger.debug(String.format("Status = %s (0x%02x)", status.getLabel(), status.getKey()));
		
		if (originalMessage == null || originalMessage.getCallbackId() != callbackId) {
			logger.warn("Already processed another send data request for this callback Id, ignoring.");
			return;
		}
		
		switch (status) {
			case COMPLETE_OK:
				ZWaveNode node = this.getNode(originalMessage.getMessageNode());
				node.resetResendCount();
				
				// in case we received a ping response and the node is alive, we proceed with the next node stage for this node.
				if (node != null && node.getNodeStage() == NodeStage.NODEBUILDINFO_PING) {
					node.advanceNodeStage();
				}
				if (incomingMessage.getMessageClass() == originalMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
					notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
					transactionCompleted.release();
					logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
				}
				return;
			case COMPLETE_NO_ACK:
			case COMPLETE_FAIL:
			case COMPLETE_NOT_IDLE:
			case COMPLETE_NOROUTE:
				try {
					handleFailedSendDataRequest(originalMessage);
				} finally {
					transactionCompleted.release();
					logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
				}
			default:
		}
	}
310108
@Override
	protected void receive() {
		while (!Thread.currentThread().isInterrupted()) {
			try {

				// Waiting for packet...
				byte[] buffer = new byte[512];
				DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
				if (multicastReceiver == null) {
					return;
				}
				multicastReceiver.receive(packet);
				processReceivedMessage(packet, buffer);

			} catch (Exception cause) {
				String msg = cause == null ? null : cause.getMessage();
				if (msg != null && msg.contains("closed")) {
					return;
				}
				logger.warn("Unexpected error occurred in UDP broadcaster!", cause);
				try {
					Thread.sleep(1000);
				} catch (Exception interrupt) {
					return;
				}
			}
		}
	}
344408
def listen_loop(self):
        

        while self.listening:
            try:
                data, address = self.sock.recvfrom(self.bufsize)
                self.receive_datagram(data, address)
                if self.stats_enabled:
                    self.stats['bytes_recieved'] += len(data)
            except socket.error as error:
                if error.errno == errno.WSAECONNRESET:
                    logger.info("connection reset")
                else:
                    raise

        logger.info("Shutting down the listener...")
470327
public void outboundMessageSent(int seqNo, long optionalWireSize, long optionalUncompressedSize) {
    for (StreamTracer tracer : tracers) {
      tracer.outboundMessageSent(seqNo, optionalWireSize, optionalUncompressedSize);
    }
  }
1193985
def datagramReceived(self, data):
        
        try:
            obj = json.loads(data)
        except ValueError, e:
            log.err(e, 'Invalid JSON in stream: %r' % data)
            return

        if u'text' in obj:
            obj = Status.fromDict(obj)
        else:
            log.msg('Unsupported object %r' % obj)
            return

        self.callback(obj)
582424
def _data(self, received_data):
        
        if self.listener.on_data(received_data) is False:
            self.stop()
            raise ListenerError(self.listener.connection_id, received_data)
961733
public void sendMessage(String message){

		byte[] datagramData = message.getBytes();
		datagramPacket.setData(datagramData);

		try {
			datagramSocket.send(datagramPacket);
		} catch (IOException e) {
			Log.e(TAG, "Failed to send datagram log " + e);
		}
	}
849690
private synchronized void processProgressEvent(DownstreamChannel channel, WrappedByteBuffer buffer) {
        LOG.entering(CLASS_NAME, "processProgressEvent", buffer);
        try {
            
            // update timestamp that is used to record the timestamp of last received message
            channel.lastMessageTimestamp.set(System.currentTimeMillis());
            channel.buffersToRead.add(buffer);

            WebSocketEmulatedDecoderListener<DownstreamChannel> decoderListener = new WebSocketEmulatedDecoderListener<DownstreamChannel>() {

                @Override
                public void messageDecoded(DownstreamChannel channel, WrappedByteBuffer message) {
                    processMessage(channel, message);
                }

                @Override
                public void messageDecoded(DownstreamChannel channel, String message) {
                    processMessage(channel, message);
                }

                @Override
                public void commandDecoded(DownstreamChannel channel, WrappedByteBuffer command) {
                    int commandByte = command.array()[0];
                    if (commandByte == 0x30 && command.array()[1] == 0x31) { //reconnect
                        // KG-5615: Set flag - but do not reconnect until request has loaded
                        LOG.fine("Reconnect command");
                        channel.reconnecting.set(true);
                    }
                    else if (commandByte == 0x30 && command.array()[1] == 0x32) {
                        channel.closing.set(true);

                        // Cancel the idle timer if running
                        stopIdleTimer(channel);
                        
                        //close frame received
                        int code = CloseCommandMessage.CLOSE_NO_STATUS;
                        String reason = null;
                        command.skip(2); //skip first 2 bytes 0x30, 0x32
                        if (command.hasRemaining()) {
                            code = command.getShort();
                        }
                        if (command.hasRemaining()) {
                            reason = command.getString(Charset.forName("UTF-8"));
                        }
                        CloseCommandMessage message = new CloseCommandMessage(code, reason);
                        listener.commandMessageReceived(channel, message);
                    }
                }

                @Override
                public void pingReceived(DownstreamChannel channel) {
                    listener.pingReceived(channel);
                }
            };

            // Prevent multiple threads from entering
            synchronized (channel.decoder) {
                channel.decoder.decode(channel, in, decoderListener);
            }
        } catch (Exception e) {
            LOG.log(Level.FINE, e.getMessage(), e);
            e.printStackTrace();
            
            listener.downstreamFailed(channel, e);
        }
    }