websocket与canvas[转]

server端还是用tomcat7的方式
客户端

[java] view plaincopy
 
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">      
  2. <html>      
  3. <head>      
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">      
  5. <title>Insert title here</title>      
  6. </head>      
  7.     
  8. <body onload="startServer()">    
  9. <canvas id="myCanvas" width="400px" height="500px">myCanvas</canvas>    
  10. <canvas id="yourCanvas" width="400px" height="500px">yourCanvas</canvas>    
  11. <div id="chatdiv" width="400px" height="500px">chatdiv</div>   
  12.   
  13. <input type="text" id="textMessage" size="20" />      
  14. <input type="button" onclick="sendMessage()" value="Send">     
  15. <input type="button" onclick="sendphoto()" value="sendphoto">      
  16. </body>   
  17. <script type="text/javascript">  
  18.     var myCanvas=document.getElementById("myCanvas");    
  19.     var context=myCanvas.getContext('2d');    
  20.     var imagewidth=myCanvas.width;  
  21.     var imageheight=myCanvas.height;  
  22.     var yourCanvas=document.getElementById("yourCanvas");    
  23.     var context2=yourCanvas.getContext('2d');   
  24.     var image = new Image();    
  25.     image.src = "haoba.jpg";    
  26.     image.onload = function(){    
  27.         context.drawImage(image,0,0);    
  28.         var imgData=context.getImageData(50,50,200,200);    
  29.         context2.putImageData(imgData,10,260);    
  30.         //ctx.putImageData(imgData,200,260,50,50,100,100);    
  31.     };    
  32.    
  33.     var ws = null;      
  34.     function startServer() {      
  35.         var url = "ws://192.168.137.27:8081/hao/msg";      
  36.         if ('WebSocket' in window) {      
  37.             ws = new WebSocket(url);      
  38.         } else if ('MozWebSocket' in window) {      
  39.             ws = new MozWebSocket(url);      
  40.         } else {      
  41.             alert('浏览器不支持');      
  42.             return;    
  43.         }      
  44.         ws.binaryType = "arraybuffer";  
  45.         ws.onopen = function() {      
  46.             alert('Opened!');      
  47.         };      
  48.         // 收到服务器发送的文本消息, event.data表示文本内容      
  49.         ws.onmessage = function(event) {   
  50.             if(event.data instanceof ArrayBuffer){  
  51.                 var bytearray = new Uint8Array(event.data);  
  52.                 var tempcanvas = yourCanvas;  
  53.                 tempcanvas.height = imageheight;  
  54.                 tempcanvas.width = imagewidth;  
  55.                 var tempcontext = tempcanvas.getContext('2d');  
  56.                 var imgdata = tempcontext.getImageData(0,0,imagewidth,imageheight);  
  57.                 var imgdatalen = imgdata.data.length;  
  58.                 for(var i=8;i<imgdatalen;i++){  
  59.                     imgdata.data[i] = bytearray[i];  
  60.                 }  
  61.                 tempcontext.putImageData(imgdata,0,0);  
  62.                 var img = document.createElement('img');  
  63.                     img.height = imageheight;  
  64.                     img.width = imagewidth;  
  65.                     img.src = tempcanvas.toDataURL();  
  66.                 var chatdiv=document.getElementById("chatdiv");  
  67.                 chatdiv.appendChild(img);  
  68.                 chatdiv.innerHTML = chatdiv.innerHTML + "<br />";  
  69.             }else{  
  70.                 alert('Receive message: ' + event.data);      
  71.             }  
  72.               
  73.         };      
  74.         ws.onclose = function() {      
  75.           alert('Closed!');      
  76.         }     
  77.         ws.onerror = function(err){  
  78.             alert(err);  
  79.         };   
  80.     }      
  81.     //发送信息      
  82.     function sendMessage(){      
  83.         var textMessage=document.getElementById("textMessage").value;      
  84.               
  85.         if(ws!=null&&textMessage!=""){      
  86.             ws.send(textMessage);      
  87.         }      
  88.     }      
  89.       
  90.     function sendphoto(){  
  91.         imagedata = context.getImageData(0, 0, imagewidth,imageheight);  
  92.         var canvaspixelarray = imagedata.data;  
  93.         var canvaspixellen = canvaspixelarray.length;  
  94.         var bytearray = new Uint8Array(canvaspixellen);  
  95.         for (var i=0;i<canvaspixellen;++i) {  
  96.             bytearray[i] = canvaspixelarray[i];  
  97.         }  
  98.         ws.send(bytearray.buffer);  
  99.         context.fillStyle = '#000000';  
  100.         context.fillRect(0, 0, imagewidth,imageheight);      
  101.     }  
  102. </script>    
  103. </html>  


tomcat7下的服务端
HelloWorldWebSocketServlet.java

[java] view plaincopy
 
  1. package com.hao;  
  2.   
  3. import java.io.DataInputStream;  
  4. import java.io.IOException;  
  5. import java.io.PrintWriter;  
  6. import java.net.Socket;  
  7. import java.net.UnknownHostException;  
  8. import java.nio.ByteBuffer;  
  9. import java.nio.CharBuffer;  
  10. import java.util.ArrayList;  
  11. import java.util.HashMap;  
  12. import java.util.Map;  
  13. import java.util.Random;  
  14.   
  15. import javax.servlet.http.HttpServletRequest;  
  16.   
  17. import org.apache.catalina.websocket.MessageInbound;  
  18. import org.apache.catalina.websocket.StreamInbound;  
  19. import org.apache.catalina.websocket.WebSocketServlet;  
  20. import org.apache.catalina.websocket.WsOutbound;  
  21.   
  22. public class HelloWorldWebSocketServlet extends WebSocketServlet {  
  23.     public static Map<String,MyMessageInbound> mmiList  = new HashMap<String,MyMessageInbound>();  
  24.   
  25.     protected StreamInbound createWebSocketInbound(String subProtocol,  
  26.             HttpServletRequest arg1) {  
  27.         return new MyMessageInbound();  
  28.     }  
  29.     public int getUserCount(){  
  30.         return mmiList.size();  
  31.     }  
  32.     private class MyMessageInbound extends MessageInbound {  
  33.         WsOutbound myoutbound;  
  34.         String mykey;  
  35.         @Override  
  36.         public void onOpen(WsOutbound outbound) {  
  37.             try {  
  38.                 System.out.println("Open Client.");  
  39.                 this.myoutbound = outbound;  
  40.                 mykey =""+System.currentTimeMillis();;  
  41.                 mmiList.put(mykey, this);  
  42.                 System.out.println("mmiList size:"+mmiList.size());  
  43.                 outbound.writeTextMessage(CharBuffer.wrap("open "+mykey));  
  44.             } catch (IOException e) {  
  45.                 e.printStackTrace();  
  46.             }  
  47.         }  
  48.   
  49.         @Override  
  50.         public void onClose(int status) {  
  51.             System.out.println("Close Client.");  
  52.             //mmiList.remove(this);  
  53.             mmiList.remove(mykey);  
  54.         }  
  55.   
  56.         @Override  
  57.         protected void onBinaryMessage(ByteBuffer arg0) throws IOException {  
  58.             System.out.println("websocket-----onBinaryMessage:"+arg0.toString());  
  59.             for (Map.Entry<String, MyMessageInbound> entry : mmiList.entrySet()) {  
  60.                     System.out.println(entry.getKey()+"--bin---");  
  61.                     MyMessageInbound mmib = (MyMessageInbound) entry.getValue();   
  62.                     mmib.myoutbound.writeBinaryMessage(arg0);  
  63.                     mmib.myoutbound.flush();  
  64.             }  
  65.         }  
  66.           
  67.         @Override  
  68.         protected void onTextMessage(CharBuffer message) throws IOException {  
  69.             System.out.println("onText--->" + message.toString());  
  70.             String[] msgarray= message.toString().split(",");  
  71.             for (Map.Entry<String, MyMessageInbound> entry : mmiList.entrySet()) {  
  72.                 System.out.println(entry.getKey()+"-----");  
  73.                   MyMessageInbound mmib = (MyMessageInbound) entry.getValue();   
  74.                   CharBuffer buffer = CharBuffer.wrap(message);  
  75.                   System.out.println(buffer);  
  76.                   mmib.myoutbound.writeTextMessage(buffer);  
  77.                   mmib.myoutbound.flush();  
  78.             }  
  79.         }  
  80.     }  
  81.   
  82.       
  83. }  


tomcat的配置文件:

[java] view plaincopy
 
    1. <?xml version="1.0" encoding="ISO-8859-1"?>  
    2. <web-app xmlns="http://java.sun.com/xml/ns/javaee"  
    3.   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    4.   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
    5.                       <a href="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"" target="_blank">http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"</a>   version="3.0"  
    6.   metadata-complete="true">  
    7. <servlet>  
    8.       <servlet-name>haomsg</servlet-name>  
    9.       <servlet-class>com.hao.HelloWorldWebSocketServlet</servlet-class>  
    10.     </servlet>  
    11.     <servlet-mapping>  
    12.       <servlet-name>haomsg</servlet-name>  
    13.       <url-pattern>/hao/msg</url-pattern>  
    14.     </servlet-mapping>  
    15. </web-app> 
posted @ 2016-06-22 15:26  火腿骑士  阅读(486)  评论(0编辑  收藏  举报