package com.hgq.websocket; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import org.apache.catalina.websocket.MessageInbound; import org.apache.catalina.websocket.StreamInbound; import org.apache.catalina.websocket.WebSocketServlet; import org.apache.catalina.websocket.WsOutbound; public class WebSocket extends WebSocketServlet { private static final long serialVersionUID = -4853540828121130946L; private static ArrayList<MyMessageInbound> mmiList = new ArrayList<MyMessageInbound>(); protected StreamInbound createWebSocketInbound(String arg0 , HttpServletRequest arg1) { String name = arg1.getParameter("uname"); return new MyMessageInbound(name); } private class MyMessageInbound extends MessageInbound { private String uname; public MyMessageInbound(){} public MyMessageInbound(String uname) { this.uname = uname; } private WsOutbound myoutbound; @Override public void onOpen(WsOutbound outbound) { try { System.out.println("Open Client."); this.myoutbound = outbound; mmiList.add(this); outbound.writeTextMessage(CharBuffer.wrap("系统消息: " + uname+ ", 欢迎进入html5聊天室!")); } catch (IOException e) { e.printStackTrace(); } } @Override public void onClose(int status) { System.out.println("Close Client."); mmiList.remove(this); } @Override public void onTextMessage(CharBuffer cb) throws IOException { System.out.println("Accept Message : " + cb); for (MyMessageInbound mmib : mmiList) { CharBuffer buffer = CharBuffer.wrap(uname + ":" + cb); mmib.myoutbound.writeTextMessage(buffer); mmib.myoutbound.flush(); } } @Override public void onBinaryMessage(ByteBuffer bb) throws IOException { } @Override public int getReadTimeout() { // 设置websocket的超时时间,单位秒 return 60000; } } }
最近下载更多
mrcao95 LV2
2023年6月26日
人工智能4708 LV11
2023年5月8日
frozenmns LV1
2023年3月11日
lironggang LV38
2023年2月16日
Tg171017 LV12
2023年2月3日
beyang LV1
2021年12月23日
1643472948 LV4
2021年12月19日
zlj-zjl LV1
2021年6月20日
zjmyyds LV1
2020年12月7日
kifura LV1
2020年12月2日
最近浏览更多
欠踹de背影 LV25
3月7日
80730176 LV7
2023年12月8日
1234567p LV1
2023年12月4日
微信网友_6627705560322048 LV1
2023年8月30日
mrcao95 LV2
2023年6月26日
luokai123 LV1
2023年6月11日
七梦辞 LV1
2023年5月25日
人工智能4708 LV11
2023年5月8日
1475406999 LV6
2023年5月4日
微信网友_6444139264921600 LV6
2023年4月30日