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; } } }