【问题标题】:Websocket @OnMessage is never firing for binary messages only textWebsocket @OnMessage 永远不会触发二进制消息只有文本
【发布时间】:2014-11-18 18:31:52
【问题描述】:

我正在用 java 代码编写与clientserver 端点的websocket 通信(使用tomcat 7.0.53 作为Web 服务器)当我使用session.getbasicremote.sendText(String) 方法发送短信时@Onmessage函数被触发和一切。但是我想在 websockets 之间发送二进制数据,因此必须使用session.getbasicremote.sendBinary(ByteBuffer)。然后应该在以下方法中读取代码,

@OnMessage
public void recieved(ByteBuffer byteBuffer)
{
    System.out.println(byteBuffer);
}

但是,当发送消息时,该方法永远不会被触发(我通过远程调试和打印语句进行了调试,以验证二进制数据是否正在发送,是的,当binary 切换到text)。有谁知道为什么从 websocket 的另一端发送数据时永远不会调用此方法?这也是通过 websocket 发送二进制数据的部分的代码。 @onError 方法也在类中,也从未调用过。

public void SendMessage() throws IOException
{
    for(int i = 0;i<MESSAGE_SIZE;i++)
        message+='\0';
    for(int i = 0;i<ID_SIZE;i++)
        id+='\0';
    ByteBuffer bbuf = ByteBuffer.allocate(1000);
    bbuf.put(id.getBytes());
    bbuf.position(33);
    bbuf.putInt(33,length);
    bbuf.position(37);
    bbuf.put(message.getBytes());
    for(Session session : sessionList)
        session.getAsyncRemote().sendBinary(bbuf);
    System.out.println("sent");
}

【问题讨论】:

    标签: java tomcat websocket tomcat7 bytebuffer


    【解决方案1】:

    添加ByteBuffer 翻转方法将实现代码现在如下所示的技巧,

    public void SendMessage() throws IOException
    {
        for(int i = 0;i<MESSAGE_SIZE;i++)
            message+='\0';
        for(int i = 0;i<ID_SIZE;i++)
            id+='\0';
        ByteBuffer bbuf = ByteBuffer.allocate(1000);
        bbuf.put(id.getBytes());
        bbuf.position(33);
        bbuf.putInt(33,length);
        bbuf.position(37);
        bbuf.put(message.getBytes());
        bbuf.flip();
        for(Session session : sessionList)
            session.getAsyncRemote().sendBinary(bbuf);
        System.out.println("sent");
    }
    

    根据API文档,翻转方法如下,"the limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded. After a sequence of channel-read or put operations, invoke this method to prepare for a sequence of channel-write or relative get operations"

    【讨论】:

    • 我将 arrayBuffer 作为var img = context.getImageData(0, 0, canvas.width, canvas.height); var binary = new Uint8Array(img.data.length); for (var i = 0; i &lt; img.data.length; i++) { binary[i] = img.data[i]; } sendBinary(binary.buffer); 发送,我没有让你的代码为我工作如何使用它。帮帮我。 onMessage 没有调用。我如何发送二进制数据
    猜你喜欢
    • 2017-04-15
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 2016-09-05
    相关资源
    最近更新 更多