@Override public void send(final Message msg) { LOGGER.debug("{} send message: {}", sessionName(), msg); session.getRemote().sendBytesByFuture(ByteBuffer.wrap(MessageEncoding.encodeMessage(msg))); }
@OnWebSocketMessage public void onMessage(byte[] buf, int offset, int length) { send(t -> t.session.getRemote().sendBytesByFuture(ByteBuffer.wrap(buf, offset, length))); }
private void send(Message message) { for (int retries = 1; retries <= systemEnvironment.getWebsocketSendRetryCount(); retries++) { try { LOG.debug("{} attempt {} to send message: {}", sessionName(), retries, message); session.getRemote().sendBytesByFuture(ByteBuffer.wrap(MessageEncoding.encodeMessage(message))); break; } catch (Throwable e) { try { LOG.debug("{} attempt {} failed to send message: {}.", sessionName(), retries, message); if (retries == systemEnvironment.getWebsocketSendRetryCount()) { bomb(e); } Thread.sleep(2000L); } catch (InterruptedException ignored) { } } } }
@Override public void write(byte[] data, int offset, int length) throws IOException { try { session.getRemote().sendBytesByFuture(ByteBuffer.wrap(data, offset, length)).get(); } catch (InterruptedException | ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
@Override public void write(byte[] data, int offset, int length) throws IOException { try { session.getRemote().sendBytesByFuture(ByteBuffer.wrap(data, offset, length)).get(); } catch (InterruptedException | ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
@Override public IWebSocketConnection sendMessage(byte[] message, int offset, int length) throws IOException { checkClosed(); ByteBuffer buf = ByteBuffer.wrap(message, offset, length); session.getRemote().sendBytesByFuture(buf); return this; }
/** * Gets the websocket session. * * @return * @throws IOException * @throws GeneralSecurityException */ protected Future<Void> sendContent(InputStream inputStream) throws IOException, GeneralSecurityException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyLarge(inputStream, baos); // generate blob byte[] contentBlob = serDe.serialize(baos.toByteArray()); // check if we need to do psk encryption contentBlob = pskFrameProcessor.processOutgoing(contentBlob, 0, contentBlob.length); return session.getRemote().sendBytesByFuture(ByteBuffer.wrap(contentBlob)); }
@Override public void onSocketOutboundBinary(ByteBuffer data) throws IOException { if (!transportStartedAtLeastOnce()) { LOG.debug("Waiting for WebSocket to be properly started..."); try { socketTransportStarted.await(); } catch (InterruptedException e) { LOG.warn("While waiting for WebSocket to be properly started, we got interrupted!! Should be okay, but you could see race conditions..."); } } LOG.trace("WS Proxy sending {} bytes out", data.remaining()); int limit = data.limit(); try { session.getRemote().sendBytesByFuture(data).get(getDefaultSendTimeOut(), TimeUnit.SECONDS); } catch (Exception e) { throw IOExceptionSupport.create(e); } // Reset back to original limit and move position to match limit indicating // that we read everything, the websocket sender clears the passed buffer // which can make it look as if nothing was written. data.limit(limit); data.position(limit); }
@Override public void onSocketOutboundBinary(ByteBuffer data) throws IOException { if (!transportStartedAtLeastOnce()) { LOG.debug("Waiting for WebSocket to be properly started..."); try { socketTransportStarted.await(); } catch (InterruptedException e) { LOG.warn("While waiting for WebSocket to be properly started, we got interrupted!! Should be okay, but you could see race conditions..."); } } LOG.trace("WS Proxy sending {} bytes out", data.remaining()); int limit = data.limit(); try { session.getRemote().sendBytesByFuture(data).get(getDefaultSendTimeOut(), TimeUnit.SECONDS); } catch (Exception e) { throw IOExceptionSupport.create(e); } // Reset back to original limit and move position to match limit indicating // that we read everything, the websocket sender clears the passed buffer // which can make it look as if nothing was written. data.limit(limit); data.position(limit); }
@Override public void onSocketOutboundBinary(ByteBuffer data) throws IOException { if (!transportStartedAtLeastOnce()) { LOG.debug("Waiting for WebSocket to be properly started..."); try { socketTransportStarted.await(); } catch (InterruptedException e) { LOG.warn("While waiting for WebSocket to be properly started, we got interrupted!! Should be okay, but you could see race conditions..."); } } LOG.trace("WS Proxy sending {} bytes out", data.remaining()); int limit = data.limit(); try { session.getRemote().sendBytesByFuture(data).get(getDefaultSendTimeOut(), TimeUnit.SECONDS); } catch (Exception e) { throw IOExceptionSupport.create(e); } // Reset back to original limit and move position to match limit indicating // that we read everything, the websocket sender clears the passed buffer // which can make it look as if nothing was written. data.limit(limit); data.position(limit); }
private void sendErrorResponse(WebSocketRequestMessage requestMessage, Response error) { if (requestMessage.hasRequestId()) { List<String> headers = new LinkedList<>(); for (String key : error.getStringHeaders().keySet()) { headers.add(key + ":" + error.getStringHeaders().getFirst(key)); } WebSocketMessage response = messageFactory.createResponse(requestMessage.getRequestId(), error.getStatus(), "Error response", headers, Optional.<byte[]>empty()); remoteEndpoint.sendBytesByFuture(ByteBuffer.wrap(response.toByteArray())); } }
@Override public void flushBuffer() throws IOException { if (!isCommitted) { byte[] body = responseBody.toByteArray(); if (body.length <= 0) { body = null; } byte[] response = messageFactory.createResponse(responseBuilder.getRequestId(), responseBuilder.getStatusCode(), responseBuilder.getMessage(), new LinkedList<>(), Optional.ofNullable(body)) .toByteArray(); endPoint.sendBytesByFuture(ByteBuffer.wrap(response)); isCommitted = true; } }
@Override public void sendToMQTT(MQTTFrame command) throws IOException { ByteSequence bytes = wireFormat.marshal(command); try { //timeout after a period of time so we don't wait forever and hold the protocol lock session.getRemote().sendBytesByFuture( ByteBuffer.wrap(bytes.getData(), 0, bytes.getLength())).get(getDefaultSendTimeOut(), TimeUnit.SECONDS); } catch (Exception e) { throw IOExceptionSupport.create(e); } }
@Override public void sendToMQTT(MQTTFrame command) throws IOException { ByteSequence bytes = wireFormat.marshal(command); try { //timeout after a period of time so we don't wait forever and hold the protocol lock session.getRemote().sendBytesByFuture( ByteBuffer.wrap(bytes.getData(), 0, bytes.getLength())).get(getDefaultSendTimeOut(), TimeUnit.SECONDS); } catch (Exception e) { throw IOExceptionSupport.create(e); } }
/** * Gets the websocket session. * * @return * @throws IOException * @throws GeneralSecurityException */ protected Future<Void> sendMessage(String action, String transactionId, String typeId, ByteBuffer payload) throws IOException, GeneralSecurityException { Envelope envelope = new Envelope(action, typeId, transactionId, payload); // generate blob byte[] envelopeBlob = serDe.serialize(envelope); // check if we need to do psk encryption envelopeBlob = pskFrameProcessor.processOutgoing(envelopeBlob, 0, envelopeBlob.length); return session.getRemote().sendBytesByFuture(ByteBuffer.wrap(envelopeBlob)); }
@Override public void sendToMQTT(MQTTFrame command) throws IOException { ByteSequence bytes = wireFormat.marshal(command); try { //timeout after a period of time so we don't wait forever and hold the protocol lock session.getRemote().sendBytesByFuture( ByteBuffer.wrap(bytes.getData(), 0, bytes.getLength())).get(getDefaultSendTimeOut(), TimeUnit.SECONDS); } catch (Exception e) { throw IOExceptionSupport.create(e); } }
Future<Void> sendMessage(DefaultWebsocket websocket, Object message) throws IOException { Future<Void> future = null; // in case there is web socket and socket connection is open - send message if (websocket != null && websocket.getSession().isOpen()) { log.trace("Sending to websocket {} -> {}", websocket.getConnectionKey(), message); if (message instanceof String) { future = websocket.getSession().getRemote().sendStringByFuture((String) message); } else if (message instanceof byte[]) { ByteBuffer buf = ByteBuffer.wrap((byte[]) message); future = websocket.getSession().getRemote().sendBytesByFuture(buf); } } return future; }
/** * Sends a message to the specified clients. * @param message message * @param websockets clients * @throws QueryException query exception */ private static void send(final Value message, final List<WebSocket> websockets) throws QueryException { // serialize contents once final List<Object> values; try { values = WsResponse.serialize(message.iter(), new SerializerOptions()); } catch(final QueryIOException ex) { throw ex.getCause(); } // send result to all clients for(final WebSocket ws : websockets) { if(!ws.isConnected()) continue; final RemoteEndpoint remote = ws.getSession().getRemote(); for(final Object value : values) { if(value instanceof ByteBuffer) { remote.sendBytesByFuture((ByteBuffer) value); } else { remote.sendStringByFuture((String) value); } } } }