HTML5 WebSocket real-time push information test demo

Test the websocket function of HTML5, and realize the real-time push information from the client to the server to the client, including pushing pictures:

websocket implements the MessageInbound class onTextMessage()/onBinaryMessage() method is responsible for information push, canvas is responsible for painting, look at the code to research and compare by yourself Ok, the source code is behind the

demo server: tomcat 7.0.47, the

browser supports websocket version 13,

note: the jar package is imported in the lib directory of tomcat: catalina.jar tomcat-coyote.jar, which needs to be deleted after publishing the project , otherwise the package conflicts! The websocket version of each browser is different and needs to be tested continuously. Use with caution! ! !

First create a service initialization class SocketService, a servlet
package com.websocket;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.catalina.websocket.MessageInbound;

public class SocketService extends HttpServlet {
    
    private static List<MessageInbound> socketList;
    
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
        SocketService.socketList = new ArrayList<MessageInbound>();
        super.init(config);
    }
    
    public static List<MessageInbound> getMessageInbound() {
        return  SocketService.socketList;
        
    }
}

Then create WebSocketImp and implement the WebSocketServlet class
package com.websocket;

import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;

public class WebSocketImp extends WebSocketServlet{
    
    protected StreamInbound createWebSocketInbound(String arg0,
            HttpServletRequest arg1) {
        // TODO Auto-generated method stub
        return new WebSocketInboundImp();
    }
}

Then there is the implementation class of MessageInbound
package com.websocket;

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 WebSocketInboundImp extends MessageInbound {
    
    /**
     * Open
     */
    protected void onOpen(WsOutbound outbound) {
        // TODO Auto-generated method stub
        SocketService.getMessageInbound().add(this);
        super.onOpen(outbound);
    }
    
    /**
     * closure
     */
    protected void onClose(int status) {
        // TODO Auto-generated method stub
        SocketService.getMessageInbound().remove(this);
        super.onClose(status);
    }
    
    
    /**
     * Stream processing
     */
    protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
        // TODO Auto-generated method stub
        for (MessageInbound bmsg : SocketService.getMessageInbound()) {
            ByteBuffer bb = ByteBuffer.wrap(arg0.array());
            WsOutbound wb = bmsg.getWsOutbound();
            wb.writeBinaryMessage(bb);
            wb.flush();
        }
    }
    
    /**
     * character processing
     */
    protected void onTextMessage(CharBuffer arg0) throws IOException {
        // TODO Auto-generated method stub
        for (MessageInbound msgib : SocketService.getMessageInbound()) {
            CharBuffer cb = CharBuffer.wrap(arg0);
            WsOutbound wb = msgib.getWsOutbound();
            wb.writeTextMessage(cb);
            wb.flush();
        }
    }

}

Then look at web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    
    
  <servlet>
      <servlet-name>SocketService</servlet-name>
      <servlet-class>com.websocket.WebSocketImp</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>SocketService</servlet-name>
      <url-pattern>/web</url-pattern>
  </servlet-mapping>
  
  <servlet>
      <servlet-name>sload</servlet-name>
      <servlet-class>com.websocket.SocketService</servlet-class>
      <load-on-startup>1</load-on-startup>
  </servlet>        
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

The last is the interface, which is rather ugly.
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  <script type="text/javascript">
      var ws;
      function web(){
          if('WebSocket' in window){
              ws = new WebSocket("ws://localhost:8080/websocket/web");
          }else{
              alert("Not support websocket");
          }
          ws.onopen = function(evt){
              //alert("op");
          }
          ws.onclose =function(evt){
              alert("close");
          }
          ws.onmessage = function(evt){
              var msg = evt.data;
              if("[object Blob]" != msg){
                  var msgdiv = document.getElementById("msgtext");
                  var span = document.createElement("span");
                  span.innerHTML = msg+"<br />";
                  msgdiv.appendChild(span);
              }else{
                  var msgdiv = document.getElementById("msgtext");
                  var span = document.createElement("span");
                  var br = document.createElement("br");
                  var can = document.createElement("canvas");
                  var context = can.getContext("2d");
                  var image = new Image();  
                    image.onload = function () {  
                //image.height  
                context.clearRect(0, 0, can.width, can.height);  
                context.drawImage(image, 0, 0, can.width, can.height);  
            }  
            image.src = URL.createObjectURL(msg);
            span.appendChild(can);
            span.appendChild(br);
            msgdiv.appendChild(span);
              }
          }
          ws.onerror = function(evt){
              alert("error");
          }
              }
          function sendmsg(){
              ws.send("游客 ("+new Date().toLocaleTimeString()+")<br />"+document.getElementById("msg").value);
          }
          function sendbmsg(){
        var inputElement = document.getElementById("bmsg");
        var fileList = inputElement.files;
        
        for ( var i = 0; i < fileList.length; i++) {
            //send
            ws.send("游客 ("+new Date().toLocaleTimeString()+")");
            //read file  
             var reader = new FileReader();
            reader.readAsArrayBuffer(fileList[i]);
            //The function responds after the file is read
            reader.onload = function loaded(evt) {
                var binaryString = evt.target.result;
                ws.send(binaryString);
            }
        }
        return false;
          }
                
  </script>
  <body onload="web();">
      <div>
          <h3>testing...</h3>
          <div id="msgtext">
          
          </div>
          <div>
              <input type="text" name="msg" id="msg" />
              <button onclick="sendmsg();">发送</button><br />
              <input type="file" name="bmsg" id="bmsg" />
              <button onclick="sendbmsg();">发送</button>
          </div>
      </div>
      
  </body>
</html>

A rendering: multiple different browsers send information to achieve synchronous push

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326850559&siteId=291194637
Recommended