java websocket 示例

来源:互联网 发布:有什么耐玩的游戏知乎 编辑:程序博客网 时间:2024/05/17 09:03

该项目运行在Tomcat7上,web.xml是3.0版本。运行tomcat后,先通过多个浏览器打开多个前台页面,然后打开模拟后台的页面,输入信息后点击send发送,所有前台页面收到消息。以下是相关程序文件。


Servlet类

import java.io.IOException;import java.nio.ByteBuffer;import java.nio.CharBuffer;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;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;/**
* websocket处理servlet 
*/public class WsServlet extends WebSocketServlet {/** *  */private static final long serialVersionUID = -2581942001009336822L;//private static final Logger log = Logger.getLogger("EchoServlet");public static List<MessageInbound> socketList = new ArrayList<MessageInbound>();public static Map<String, MessageInbound> socketMap = new HashMap<String, MessageInbound>();public static List<WebSocketMessageInbound> connsList = new ArrayList<WebSocketMessageInbound>();protected StreamInbound createWebSocketInbound(String subProtocol,HttpServletRequest request){return new WebSocketMessageInbound();}public class WebSocketMessageInbound extends MessageInbound{protected void onClose(int status){super.onClose(status);socketList.remove(this);socketMap.remove(String.valueOf(this.hashCode()));}protected void onOpen(WsOutbound outbound){super.onOpen(outbound);socketList.add(this);socketMap.put(String.valueOf(this.hashCode()), this);}//@Overrideprotected void onBinaryMessage(ByteBuffer message) throws IOException System.out.println("onBinarymessage");}@Overrideprotected void onTextMessage(CharBuffer message) throws IOException {// TODO Auto-generated method stubSystem.out.println("onTextMessage>>>>"+this.hashCode());for(MessageInbound messageInbound : socketList){CharBuffer buffer = CharBuffer.wrap(message);WsOutbound outbound = messageInbound.getWsOutbound();outbound.writeTextMessage(buffer);outbound.flush();}}}}


import java.io.IOException;import java.nio.CharBuffer;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.catalina.websocket.MessageInbound;import org.apache.catalina.websocket.WsOutbound;/*
*模拟后台servlet
*/public class HoutaiServlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String s = new String(req.getParameter("msg").getBytes(), "GBK");if(s != null && !"".equals(s)){//for(MessageInbound messageInbound : WsServlet.socketList){for(int i = 0, size = WsServlet.socketList.size(); i < size; i++){MessageInbound messageInbound = WsServlet.socketList.get(i); CharBuffer buffer = CharBuffer.wrap(s);WsOutbound outbound = messageInbound.getWsOutbound();outbound.writeTextMessage(buffer);outbound.flush();}}req.getRequestDispatcher("houtai.html").forward(req, resp);  ;}}

前台页面

<!DOCTYPE html><html>  <head>    <title>WebSockete Demo</title>    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="this is my page">    <meta http-equiv="content-type" content="text/html; charset=UTF-8">        <!--<link rel="stylesheet" type="text/css" href="./styles.css">--><script type="text/javascript">//验证浏览器是否支持WebSocket协议if(!window.WebSocket){alert("WebSockeet not supported by this browser!");}var ws;function display(){ws = new WebSocket("ws://localhost:8081/wstest/websocket");//监听消息ws.onmessage = function(event){log(event.data);} //关闭WebSocketws.onclose = function(event){}//打开WebSocketws.onopen = function(event){ws.send("Hello,Server");}ws.onerror = function(event){}}var log = function(s){if(document.readyState !== "complete"){log.buffer.pust(s);}else{document.getElementById("contendId").innerHTML += (s + "\n");}}function sendMsg(){var msg = document.getElementById("messageId");ws.send(msg.value);document.getElementById("messageId").value="";}</script>  </head>    <body onload="display();">    <div id="valueLabel"></div>    <textarea rows="20" cols="30" id="contendId"></textarea>    <br/>    <input name="message" id="messageId"/>    <button id="sendButton" onClick="javascript:sendMsg()">Send</button>  </body></html>

模拟后台页面

<!DOCTYPE html><html>  <head>    <title>WebSockete Demo</title>    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="this is my page">    <meta http-equiv="content-type" content="text/html; charset=UTF-8">        <!--<link rel="stylesheet" type="text/css" href="./styles.css">--><script type="text/javascript">//验证浏览器是否支持WebSocket协议function sendMsg(){var msg = document.getElementById("messageId");f.submit();//document.getElementById("messageId").value="";}</script>  </head>    <body onload="display();">  <form id="f" action="http://localhost:8081/wstest/houtai" method="post">    <div id="valueLabel"></div>    <textarea rows="20" cols="30" id="contendId"></textarea>    <br/>    <input name="msg" id="messageId"/>    <button id="sendButton" onClick="javascript:sendMsg()">Send</button>  </form>  </body></html>

web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>wstest2</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>    <servlet>  <servlet-name>websocket</servlet-name>  <servlet-class>WsServlet</servlet-class>  <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>    <servlet-name>websocket</servlet-name>    <url-pattern>/websocket</url-pattern>      </servlet-mapping>    <servlet>  <servlet-name>houtai</servlet-name>  <servlet-class>HoutaiServlet</servlet-class>    </servlet>    <servlet-mapping>    <servlet-name>houtai</servlet-name>    <url-pattern>/houtai</url-pattern>      </servlet-mapping>  </web-app>





0 0