java.lang.IllegalStateException: The remote endpoint was in state [BINARY_PARTIAL_WRITING] 的解决方案

曾经有一个bug有关websocket丢包的问题,情景是一个用户向服务器所有用户发广播,在手机端出现丢包,程序报错,在网上搜了好久没找到答案,后来同事搜了括号里的关键词,终于

在stack overflow搜到,为了防止有同样问题的小伙伴再走弯路,记一下咯

Wrap your code in a synchronized method and funnel all calls through this new method. It appears the tomcat web socket cannot handle multiple messages being placed on the same websocket session at the same time. I have code which has been running flawlessly under Glassfish and fell apart instantly when I moved to Tomcat. I then altered my code as explained above and all my problems went away....and there was much rejoicing.

意思就是tomcat上不能放置多条消息,一个用户向服务器所有用户发广播,在手机端出现丢包,程序报错,看下代码估计就懂   

 //广播;
    public synchronized void broadcast(Object object, int wsstype, String info) {
        try {
            Iterator<WebSocketSession> it = WebSocketSessions.iterator();
            while (it.hasNext()) {
                WebSocketSession webSocketSession = it.next();
                try {
                    if (webSocketSession.isOpen()) {
                        send(object, wsstype, info, webSocketSession);
                    } else {
                        it.remove();
                    }
                } catch (Exception e) {
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public synchronized void send(Object object, int wsstype, String info, WebSocketSession webSocketSession) {
        JacksonManager jm = JacksonManager.getInstance();
        ObjectNode json = jm.createObjectNode();
        json.put("status", 0);
        json.putPOJO("info", info);
        json.putPOJO("data", object);
        ByteBuffer sendbb = null;
        try {
            sendbb = BytesCommon.changebtyes(jm.toJson(json), wsstype);
            BinaryMessage binaryMessage = new BinaryMessage(sendbb);
            synchronized (webSocketSession) {
                webSocketSession.sendMessage(binaryMessage);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值