tomcat7 websocket demo
參考:
* http://www.eoeandroid.com/thread-272068-1-1.html
* http://blog.csdn.net/baiyang_liu/article/details/8261089
ChatWebSocketServlet.java
package jmind.ws.tomcat; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; 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; /** * * chat.jsp * @author wbxie * 2013-11-6 */ @SuppressWarnings("deprecation") //@WebServlet("/ws/chat") public class ChatWebSocketServlet extends WebSocketServlet { private final Map<Integer, WsOutbound> map = new HashMap<Integer, WsOutbound>(); /** * */ private static final long serialVersionUID = -1058445282919079067L; @Override protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest request) { return new ChatMessageInbound(); } class ChatMessageInbound extends MessageInbound { @Override protected void onOpen(WsOutbound outbound) { map.put(outbound.hashCode(), outbound); super.onOpen(outbound); } @Override protected void onClose(int status) { map.remove(getWsOutbound().hashCode()); super.onClose(status); } @Override protected void onBinaryMessage(ByteBuffer buffer) throws IOException { // TODO Auto-generated method stub } @Override protected void onTextMessage(CharBuffer buffer) throws IOException { String msg = buffer.toString(); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); msg = " <font color=green>匿名用户 " + sdf.format(date) + "</font><br/> " + msg; broadcast(msg); } private void broadcast(String msg) { Set<Integer> set = map.keySet(); for (Integer integer : set) { WsOutbound outbound = map.get(integer); CharBuffer buffer = CharBuffer.wrap(msg); try { outbound.writeTextMessage(buffer); outbound.flush(); } catch (IOException e) { e.printStackTrace(); } } } } }
相关推荐
柳木木的IT 2020-11-04
joynet00 2020-09-23
wenf00 2020-09-14
蓝色深海 2020-08-16
wuychn 2020-08-16
取个好名字真难 2020-08-06
darylove 2020-06-26
shufen0 2020-06-20
Lovexinyang 2020-06-14
WangBowen 2020-06-14
firejq 2020-06-14
hjhmpl 2020-06-14
水痕 2020-06-07
guozewei0 2020-06-06
woniyu 2020-06-02
取个好名字真难 2020-06-01
guozewei0 2020-05-28
woniyu 2020-05-26