【问题标题】:Websockets- send binary data as chunksWebsockets-将二进制数据作为块发送
【发布时间】:2015-05-06 12:13:15
【问题描述】:

可以在 websockets 中以块的形式发送二进制数据。?

我正在使用以下代码发送二进制数据, 未来 f = session.getAsyncRemote().sendbinary(bytebuffer);

这会将数据作为整体传输。那么任何人都可以建议我如何将数据作为块异步发送,或者它有任何 java 库来实现这个概念。

【问题讨论】:

标签: java websocket


【解决方案1】:

nv-websocket-client 中的WebSocket 类具有发送分段帧的方法。以下代码(在 README.md 中找到)显示了如何发送由 3 个碎片帧组成的文本消息(“你好吗?”)。你可以用类似的方式发送分段的二进制帧。

// The first frame must be either a text frame or a binary frame.
// And its FIN bit must be cleared.
WebSocketFrame firstFrame = WebSocketFrame
    .createTextFrame("How ")
    .setFin(false);

// Subsequent frames must be continuation frames. The FIN bit of
// all continuation frames except the last one must be cleared.
// Note that the FIN bit of frames returned from
// WebSocketFrame.createContinuationFrame() method is cleared,
// so the example below does not clear the FIN bit explicitly.
WebSocketFrame secondFrame = WebSocketFrame
    .createContinuationFrame("are ");

// The last frame must be a continuation frame with the FIN bit
// set. Note that the FIN bit of frames returned from
// WebSocketFrame.createContinuationFrame methods is cleared,
// so the FIN bit of the last frame must be set explicitly.
WebSocketFrame lastFrame = WebSocketFrame
    .createContinuationFrame("you?")
    .setFin(true);

// Send a text message which consists of 3 frames.
ws.sendFrame(firstFrame)
  .sendFrame(secondFrame)
  .sendFrame(lastFrame);

或者,也可以像上面那样做。

// Send a text message which consists of 3 frames.
ws.sendText("How ", false)
  .sendContinuation("are ")
  .sendContinuation("you?", true);

JavaDoc

http://takahikokawasaki.github.io/nv-websocket-client/

GitHub

https://github.com/TakahikoKawasaki/nv-websocket-client

博客

WebSocket 客户端库(Java SE 1.5+,Android)
http://darutk-oboegaki.blogspot.jp/2015/05/websocket-client-library-java-se-15.html

【讨论】:

    猜你喜欢
    • 2013-03-07
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    相关资源
    最近更新 更多