package com.web;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;

public class MyMessageInbound extends MessageInbound {
    private int userIdName = 0;

    public int getUserIdName() {
        return userIdName;
    }

    protected void onOpen(WsOutbound outbound) {
        super.onOpen(outbound);
        userIdName = outbound.hashCode();
        EchoServlet.getSocketList().add(this);
    }

    protected void onClose(int status) {
        EchoServlet.getSocketList().remove(this);
        super.onClose(status);
    }

    // 有二进制消息数据到达,比如音频等文件传输
    @Override
    protected void onBinaryMessage(ByteBuffer buffer) throws IOException {
    }

    @Override
    protected void onTextMessage(CharBuffer buffer) throws IOException {
        String msgOriginal = buffer.toString();
       System.out.println("msgOriginal:::"+msgOriginal);
        int startIndex = msgOriginal.indexOf("!@#$%");
        
        
        String nikeName = msgOriginal.substring(0, startIndex);
     
        
        String textMsg = msgOriginal.substring(startIndex + 5);
        // 将字符数组包装到缓冲区中
        // 给定的字符数组将支持新缓冲区;即缓冲区修改将导致数组修改,反之亦然

        String countMsg = EchoServlet.getSocketList().size() + "人同时在线";
        System.out.println("同时在线人数:::"+countMsg);
        	
        
        String msg1 =  "<div class='style2'><img src='img/emo_02.gif' />"+nikeName + ": " + textMsg+"</div>" ;
        String msg2 = "<div class='style2'><img src='img/emo_01.gif' /><span style='color:red'>"+nikeName+"</span> " + textMsg+"</div>" ;

        
        System.out.println(EchoServlet.getSocketList().size());
        
        for (MyMessageInbound messageInbound : EchoServlet.getSocketList()) {
            CharBuffer msgBuffer1 = CharBuffer.wrap(msg1);
            CharBuffer msgBuffer2 = CharBuffer.wrap(msg2);
            WsOutbound outbound = messageInbound.getWsOutbound();
            if (messageInbound.getUserIdName() != this.getUserIdName()) {
                outbound.writeTextMessage(msgBuffer1);
                outbound.flush();
            } else {
                outbound.writeTextMessage(msgBuffer2);
                outbound.flush();
            }
        }
    }
}
最近下载更多
wuying8208  LV15 2023年7月1日
WASDZZ  LV13 2022年7月25日
sjc199  LV2 2022年6月13日
wanglinddad  LV54 2022年4月17日
waityou2000317  LV4 2022年3月10日
luweiyuan  LV3 2020年12月8日
doremi  LV6 2020年5月17日
dhb123  LV5 2020年5月1日
shiqianxi  LV1 2020年2月19日
taylor503  LV6 2019年12月9日
最近浏览更多
dafeiyu  LV10 3月1日
张英伟 2023年12月29日
暂无贡献等级
3263394665  LV9 2023年12月1日
wuying8208  LV15 2023年7月1日
小白会染色 2023年6月29日
暂无贡献等级
gayalee 2023年6月9日
暂无贡献等级
tangruirui 2023年5月23日
暂无贡献等级
微信网友_6444139264921600  LV6 2023年4月29日
xiexiaoming05  LV14 2023年1月11日
kkkkks  LV1 2022年12月30日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友