org.springframework.web.socket.BinaryMessage Java Examples
The following examples show how to use
org.springframework.web.socket.BinaryMessage.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebSocketStompClientTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void sendWebSocketBinary() throws Exception { StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND); accessor.setDestination("/b"); accessor.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM); byte[] payload = "payload".getBytes(UTF_8); getTcpConnection().send(MessageBuilder.createMessage(payload, accessor.getMessageHeaders())); ArgumentCaptor<BinaryMessage> binaryMessageCaptor = ArgumentCaptor.forClass(BinaryMessage.class); verify(this.webSocketSession).sendMessage(binaryMessageCaptor.capture()); BinaryMessage binaryMessage = binaryMessageCaptor.getValue(); assertNotNull(binaryMessage); assertEquals("SEND\ndestination:/b\ncontent-type:application/octet-stream\ncontent-length:7\n\npayload\0", new String(binaryMessage.getPayload().array(), UTF_8)); }
Example #2
Source File: AbstractWebSocketSession.java From java-technology-stack with MIT License | 6 votes |
@Override public final void sendMessage(WebSocketMessage<?> message) throws IOException { checkNativeSessionInitialized(); if (logger.isTraceEnabled()) { logger.trace("Sending " + message + ", " + this); } if (message instanceof TextMessage) { sendTextMessage((TextMessage) message); } else if (message instanceof BinaryMessage) { sendBinaryMessage((BinaryMessage) message); } else if (message instanceof PingMessage) { sendPingMessage((PingMessage) message); } else if (message instanceof PongMessage) { sendPongMessage((PongMessage) message); } else { throw new IllegalStateException("Unexpected WebSocketMessage type: " + message); } }
Example #3
Source File: WebSocketStompClient.java From java-technology-stack with MIT License | 6 votes |
public List<Message<byte[]>> decode(WebSocketMessage<?> webSocketMessage) { List<Message<byte[]>> result = Collections.emptyList(); ByteBuffer byteBuffer; if (webSocketMessage instanceof TextMessage) { byteBuffer = ByteBuffer.wrap(((TextMessage) webSocketMessage).asBytes()); } else if (webSocketMessage instanceof BinaryMessage) { byteBuffer = ((BinaryMessage) webSocketMessage).getPayload(); } else { return result; } result = this.bufferingDecoder.decode(byteBuffer); if (result.isEmpty()) { if (logger.isTraceEnabled()) { logger.trace("Incomplete STOMP frame content received, bufferSize=" + this.bufferingDecoder.getBufferSize() + ", bufferSizeLimit=" + this.bufferingDecoder.getBufferSizeLimit() + "."); } } return result; }
Example #4
Source File: WebSocketMqtt.java From WeEvent with Apache License 2.0 | 6 votes |
@Override protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) { try { MqttMessage msg = decode(message); if (msg.decoderResult().isFailure()) { Optional<MqttMessage> rsp = this.protocolProcess.getDecodeFailureRsp(msg); rsp.ifPresent(mqttMessage -> send2Remote(session, mqttMessage)); log.error("decode message failed, close session"); this.closeSession(session); return; } this.handleSingleMessage(msg, session); } catch (BrokerException e) { log.error("close session, {}", session.getId()); this.closeSession(session); } }
Example #5
Source File: WebSocketStompClientTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void sendWebSocketBinary() throws Exception { StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND); accessor.setDestination("/b"); accessor.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM); byte[] payload = "payload".getBytes(StandardCharsets.UTF_8); getTcpConnection().send(MessageBuilder.createMessage(payload, accessor.getMessageHeaders())); ArgumentCaptor<BinaryMessage> binaryMessageCaptor = ArgumentCaptor.forClass(BinaryMessage.class); verify(this.webSocketSession).sendMessage(binaryMessageCaptor.capture()); BinaryMessage binaryMessage = binaryMessageCaptor.getValue(); assertNotNull(binaryMessage); assertEquals("SEND\ndestination:/b\ncontent-type:application/octet-stream\ncontent-length:7\n\npayload\0", new String(binaryMessage.getPayload().array(), StandardCharsets.UTF_8)); }
Example #6
Source File: WebSocketStompClientTests.java From spring-analysis-note with MIT License | 6 votes |
@Test @SuppressWarnings({"unchecked", "rawtypes"}) public void handleWebSocketMessageBinary() throws Exception { String text = "SEND\na:alpha\n\nMessage payload\0"; connect().handleMessage(this.webSocketSession, new BinaryMessage(text.getBytes(StandardCharsets.UTF_8))); ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class); verify(this.stompSession).handleMessage(captor.capture()); Message<byte[]> message = captor.getValue(); assertNotNull(message); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); StompHeaders headers = StompHeaders.readOnlyStompHeaders(accessor.toNativeHeaderMap()); assertEquals(StompCommand.SEND, accessor.getCommand()); assertEquals("alpha", headers.getFirst("a")); assertEquals("Message payload", new String(message.getPayload(), StandardCharsets.UTF_8)); }
Example #7
Source File: WebSocketStompClientTests.java From java-technology-stack with MIT License | 6 votes |
@Test @SuppressWarnings({"unchecked", "rawtypes"}) public void handleWebSocketMessageBinary() throws Exception { String text = "SEND\na:alpha\n\nMessage payload\0"; connect().handleMessage(this.webSocketSession, new BinaryMessage(text.getBytes(StandardCharsets.UTF_8))); ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class); verify(this.stompSession).handleMessage(captor.capture()); Message<byte[]> message = captor.getValue(); assertNotNull(message); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); StompHeaders headers = StompHeaders.readOnlyStompHeaders(accessor.toNativeHeaderMap()); assertEquals(StompCommand.SEND, accessor.getCommand()); assertEquals("alpha", headers.getFirst("a")); assertEquals("Message payload", new String(message.getPayload(), StandardCharsets.UTF_8)); }
Example #8
Source File: WebSocketStompClientTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void sendWebSocketBinary() throws Exception { StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND); accessor.setDestination("/b"); accessor.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM); byte[] payload = "payload".getBytes(StandardCharsets.UTF_8); getTcpConnection().send(MessageBuilder.createMessage(payload, accessor.getMessageHeaders())); ArgumentCaptor<BinaryMessage> binaryMessageCaptor = ArgumentCaptor.forClass(BinaryMessage.class); verify(this.webSocketSession).sendMessage(binaryMessageCaptor.capture()); BinaryMessage binaryMessage = binaryMessageCaptor.getValue(); assertNotNull(binaryMessage); assertEquals("SEND\ndestination:/b\ncontent-type:application/octet-stream\ncontent-length:7\n\npayload\0", new String(binaryMessage.getPayload().array(), StandardCharsets.UTF_8)); }
Example #9
Source File: WebsocketOutputStream.java From TrackRay with GNU General Public License v3.0 | 6 votes |
@Override public void write(byte[] buf, int off, int len) { if (webSocketSession!=null) { try { Charset cs = Charset.forName("UTF-8"); ByteBuffer bb = ByteBuffer.allocate(buf.length); bb.put(buf); bb.flip(); CharBuffer cb = cs.decode(bb); char[] array = cb.array(); StringBuffer buffer = new StringBuffer(); buffer.append(array, off, len); TextMessage textMessage = new TextMessage(buffer.toString()); webSocketSession.sendMessage(textMessage); } catch (IOException e) { BinaryMessage binaryMessage = new BinaryMessage(buf, off, len, false); try { webSocketSession.sendMessage(binaryMessage); } catch (IOException e1) { e1.printStackTrace(); } } } }
Example #10
Source File: WebSocketServerHandler.java From redtorch with MIT License | 6 votes |
public boolean sendDataByNodeId(int nodeId, byte[] data) { String tragetSessionId = nodeIdSessionIdMap.get(nodeId); if (tragetSessionId == null) { logger.error("发送RPC错误,未找到目标节点ID对应的会话ID,目标节点ID:{}", nodeId); return false; } ThreadSafeWebSocketSession session = sessionIdSessionMap.get(tragetSessionId); if (session == null) { logger.error("发送二进制数据错误,未能找到会话,目标节点ID:{},会话ID:{}", nodeId, tragetSessionId); return false; } if (!session.isOpen()) { logger.error("发送二进制数据错误,会话处于关闭状态,目标节点ID:{},会话ID:{}", nodeId, tragetSessionId); return false; } BinaryMessage message = new BinaryMessage(data); try { session.sendMessage(message); return true; } catch (IOException e) { logger.error("发送二进制数据错误,目标节点ID:{},会话ID:{}", nodeId, tragetSessionId, e); return false; } }
Example #11
Source File: RtWebSocketClient.java From redtorch with MIT License | 6 votes |
public boolean sendData(byte[] data) { if (webSocketSession == null) { logger.error("发送二进制数据错误,未能找到会话"); return false; } if (!webSocketSession.isOpen()) { logger.error("发送二进制数据错误,会话处于关闭状态,会话ID:{}", webSocketSession.getId()); return false; } BinaryMessage message = new BinaryMessage(data); try { webSocketSession.sendMessage(message); return true; } catch (IOException e) { logger.error("发送二进制数据错误,会话ID:{}", webSocketSession.getId(), e); return false; } }
Example #12
Source File: AbstractWebSocketSession.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Override public final void sendMessage(WebSocketMessage<?> message) throws IOException { checkNativeSessionInitialized(); Assert.isTrue(isOpen(), "Cannot send message after connection closed."); if (logger.isTraceEnabled()) { logger.trace("Sending " + message + ", " + this); } if (message instanceof TextMessage) { sendTextMessage((TextMessage) message); } else if (message instanceof BinaryMessage) { sendBinaryMessage((BinaryMessage) message); } else if (message instanceof PingMessage) { sendPingMessage((PingMessage) message); } else if (message instanceof PongMessage) { sendPongMessage((PongMessage) message); } else { throw new IllegalStateException("Unexpected WebSocketMessage type: " + message); } }
Example #13
Source File: WebSocketStompClient.java From spring4-understanding with Apache License 2.0 | 6 votes |
public List<Message<byte[]>> decode(WebSocketMessage<?> webSocketMessage) { List<Message<byte[]>> result = Collections.<Message<byte[]>>emptyList(); ByteBuffer byteBuffer; if (webSocketMessage instanceof TextMessage) { byteBuffer = ByteBuffer.wrap(((TextMessage) webSocketMessage).asBytes()); } else if (webSocketMessage instanceof BinaryMessage) { byteBuffer = ((BinaryMessage) webSocketMessage).getPayload(); } else { return result; } result = this.bufferingDecoder.decode(byteBuffer); if (result.isEmpty()) { if (logger.isTraceEnabled()) { logger.trace("Incomplete STOMP frame content received, bufferSize=" + this.bufferingDecoder.getBufferSize() + ", bufferSizeLimit=" + this.bufferingDecoder.getBufferSizeLimit() + "."); } } return result; }
Example #14
Source File: OfframpWebSocketHandlerTest.java From data-highway with Apache License 2.0 | 6 votes |
@Test public void handleBinaryMessage() throws Exception { Message<String> message = new Message<>(0, 1L, 1, 1L, "a"); BinaryMessage binaryMessage = new BinaryMessage((new ObjectMapper()).writeValueAsBytes(message)); String refUtf8 = new String(binaryMessage.getPayload().array(), UTF_8); String refUtf16 = new String(binaryMessage.getPayload().array(), UTF_16); underTest.afterConnectionEstablished(session); underTest.handleBinaryMessage(session, binaryMessage); ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class); verify(service).onEvent(valueCapture.capture()); String out = valueCapture.getValue(); assertEquals(refUtf8, out); assertNotEquals(refUtf16, out); }
Example #15
Source File: WebSocketStompClientTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void handleWebSocketMessageBinary() throws Exception { String text = "SEND\na:alpha\n\nMessage payload\0"; connect().handleMessage(this.webSocketSession, new BinaryMessage(text.getBytes(UTF_8))); ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class); verify(this.stompSession).handleMessage(captor.capture()); Message<byte[]> message = captor.getValue(); assertNotNull(message); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); StompHeaders headers = StompHeaders.readOnlyStompHeaders(accessor.toNativeHeaderMap()); assertEquals(StompCommand.SEND, accessor.getCommand()); assertEquals("alpha", headers.getFirst("a")); assertEquals("Message payload", new String(message.getPayload(), UTF_8)); }
Example #16
Source File: TextWebSocketHandler.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) { try { session.close(CloseStatus.NOT_ACCEPTABLE.withReason("Binary messages not supported")); } catch (IOException ex) { // ignore } }
Example #17
Source File: AbstractWebSocketHandler.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { if (message instanceof TextMessage) { handleTextMessage(session, (TextMessage) message); } else if (message instanceof BinaryMessage) { handleBinaryMessage(session, (BinaryMessage) message); } else if (message instanceof PongMessage) { handlePongMessage(session, (PongMessage) message); } else { throw new IllegalStateException("Unexpected WebSocket message type: " + message); } }
Example #18
Source File: StandardWebSocketHandlerAdapter.java From spring4-understanding with Apache License 2.0 | 5 votes |
private void handleBinaryMessage(javax.websocket.Session session, ByteBuffer payload, boolean isLast) { BinaryMessage binaryMessage = new BinaryMessage(payload, isLast); try { this.handler.handleMessage(this.wsSession, binaryMessage); } catch (Throwable ex) { ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger); } }
Example #19
Source File: JettyWebSocketHandlerAdapter.java From spring4-understanding with Apache License 2.0 | 5 votes |
@OnWebSocketMessage public void onWebSocketBinary(byte[] payload, int offset, int length) { BinaryMessage message = new BinaryMessage(payload, offset, length, true); try { this.webSocketHandler.handleMessage(this.wsSession, message); } catch (Throwable ex) { ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger); } }
Example #20
Source File: WebSocketStompClient.java From spring4-understanding with Apache License 2.0 | 5 votes |
public WebSocketMessage<?> encode(Message<byte[]> message, Class<? extends WebSocketSession> sessionType) { StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); Assert.notNull(accessor); byte[] payload = message.getPayload(); byte[] bytes = ENCODER.encode(accessor.getMessageHeaders(), payload); boolean useBinary = (payload.length > 0 && !(SockJsSession.class.isAssignableFrom(sessionType)) && MimeTypeUtils.APPLICATION_OCTET_STREAM.isCompatibleWith(accessor.getContentType())); return (useBinary ? new BinaryMessage(bytes) : new TextMessage(bytes)); }
Example #21
Source File: StompSubProtocolHandlerTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void handleMessageToClientWithBinaryWebSocketMessage() { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE); headers.setMessageId("mess0"); headers.setSubscriptionId("sub0"); headers.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM); headers.setDestination("/queue/foo"); // Non-empty payload byte[] payload = new byte[1]; Message<byte[]> message = MessageBuilder.createMessage(payload, headers.getMessageHeaders()); this.protocolHandler.handleMessageToClient(this.session, message); assertEquals(1, this.session.getSentMessages().size()); WebSocketMessage<?> webSocketMessage = this.session.getSentMessages().get(0); assertTrue(webSocketMessage instanceof BinaryMessage); // Empty payload payload = EMPTY_PAYLOAD; message = MessageBuilder.createMessage(payload, headers.getMessageHeaders()); this.protocolHandler.handleMessageToClient(this.session, message); assertEquals(2, this.session.getSentMessages().size()); webSocketMessage = this.session.getSentMessages().get(1); assertTrue(webSocketMessage instanceof TextMessage); }
Example #22
Source File: StompSubProtocolHandlerTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void handleMessageToClientWithBinaryWebSocketMessage() { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE); headers.setMessageId("mess0"); headers.setSubscriptionId("sub0"); headers.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM); headers.setDestination("/queue/foo"); // Non-empty payload byte[] payload = new byte[1]; Message<byte[]> message = MessageBuilder.createMessage(payload, headers.getMessageHeaders()); this.protocolHandler.handleMessageToClient(this.session, message); assertEquals(1, this.session.getSentMessages().size()); WebSocketMessage<?> webSocketMessage = this.session.getSentMessages().get(0); assertTrue(webSocketMessage instanceof BinaryMessage); // Empty payload payload = EMPTY_PAYLOAD; message = MessageBuilder.createMessage(payload, headers.getMessageHeaders()); this.protocolHandler.handleMessageToClient(this.session, message); assertEquals(2, this.session.getSentMessages().size()); webSocketMessage = this.session.getSentMessages().get(1); assertTrue(webSocketMessage instanceof TextMessage); }
Example #23
Source File: WebSocketStompClient.java From java-technology-stack with MIT License | 5 votes |
public WebSocketMessage<?> encode(Message<byte[]> message, Class<? extends WebSocketSession> sessionType) { StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); Assert.notNull(accessor, "No StompHeaderAccessor available"); byte[] payload = message.getPayload(); byte[] bytes = ENCODER.encode(accessor.getMessageHeaders(), payload); boolean useBinary = (payload.length > 0 && !(SockJsSession.class.isAssignableFrom(sessionType)) && MimeTypeUtils.APPLICATION_OCTET_STREAM.isCompatibleWith(accessor.getContentType())); return (useBinary ? new BinaryMessage(bytes) : new TextMessage(bytes)); }
Example #24
Source File: WebSocketHandlerTest.java From data-highway with Apache License 2.0 | 5 votes |
@Override public void afterConnectionEstablished(WebSocketSession session) throws java.io.IOException { ObjectMapper mapper = new ObjectMapper(); String event = mapper.writeValueAsString(TestMessage.getTestMessage()); int half = event.length() / 2; String part1 = event.substring(0, half); String part2 = event.substring(half); session.sendMessage(new BinaryMessage(part1.getBytes(UTF_8), false)); session.sendMessage(new BinaryMessage(part2.getBytes(UTF_8), true)); }
Example #25
Source File: JettyWebSocketHandlerAdapter.java From java-technology-stack with MIT License | 5 votes |
@OnWebSocketMessage public void onWebSocketBinary(byte[] payload, int offset, int length) { BinaryMessage message = new BinaryMessage(payload, offset, length, true); try { this.webSocketHandler.handleMessage(this.wsSession, message); } catch (Throwable ex) { ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger); } }
Example #26
Source File: StandardWebSocketHandlerAdapter.java From java-technology-stack with MIT License | 5 votes |
private void handleBinaryMessage(javax.websocket.Session session, ByteBuffer payload, boolean isLast) { BinaryMessage binaryMessage = new BinaryMessage(payload, isLast); try { this.handler.handleMessage(this.wsSession, binaryMessage); } catch (Throwable ex) { ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger); } }
Example #27
Source File: StompSubProtocolHandlerTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void handleMessageToClientWithBinaryWebSocketMessage() { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE); headers.setMessageId("mess0"); headers.setSubscriptionId("sub0"); headers.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM); headers.setDestination("/queue/foo"); // Non-empty payload byte[] payload = new byte[1]; Message<byte[]> message = MessageBuilder.createMessage(payload, headers.getMessageHeaders()); this.protocolHandler.handleMessageToClient(this.session, message); assertEquals(1, this.session.getSentMessages().size()); WebSocketMessage<?> webSocketMessage = this.session.getSentMessages().get(0); assertTrue(webSocketMessage instanceof BinaryMessage); // Empty payload payload = EMPTY_PAYLOAD; message = MessageBuilder.createMessage(payload, headers.getMessageHeaders()); this.protocolHandler.handleMessageToClient(this.session, message); assertEquals(2, this.session.getSentMessages().size()); webSocketMessage = this.session.getSentMessages().get(1); assertTrue(webSocketMessage instanceof TextMessage); }
Example #28
Source File: StandardWebSocketHandlerAdapter.java From spring-analysis-note with MIT License | 5 votes |
private void handleBinaryMessage(javax.websocket.Session session, ByteBuffer payload, boolean isLast) { BinaryMessage binaryMessage = new BinaryMessage(payload, isLast); try { this.handler.handleMessage(this.wsSession, binaryMessage); } catch (Throwable ex) { ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger); } }
Example #29
Source File: AbstractWebSocketHandler.java From spring-analysis-note with MIT License | 5 votes |
@Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { if (message instanceof TextMessage) { handleTextMessage(session, (TextMessage) message); } else if (message instanceof BinaryMessage) { handleBinaryMessage(session, (BinaryMessage) message); } else if (message instanceof PongMessage) { handlePongMessage(session, (PongMessage) message); } else { throw new IllegalStateException("Unexpected WebSocket message type: " + message); } }
Example #30
Source File: JettyWebSocketHandlerAdapter.java From spring-analysis-note with MIT License | 5 votes |
@OnWebSocketMessage public void onWebSocketBinary(byte[] payload, int offset, int length) { BinaryMessage message = new BinaryMessage(payload, offset, length, true); try { this.webSocketHandler.handleMessage(this.wsSession, message); } catch (Throwable ex) { ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger); } }