参考[url]http://www.adobe.com/devnet/archive/html5/articles/real-time-data-exchange-in-html5-with-websockets.html
[/url]
server端还是用tomcat7的方式
客户端
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body onload="startServer()">
<canvas id="myCanvas" width="400px" height="500px">myCanvas</canvas>
<canvas id="yourCanvas" width="400px" height="500px">yourCanvas</canvas>
<div id="chatdiv" width="400px" height="500px">chatdiv</div>
<input type="text" id="textMessage" size="20" />
<input type="button" onclick="sendMessage()" value="Send">
<input type="button" onclick="sendphoto()" value="sendphoto">
</body>
<script type="text/javascript">
var myCanvas=document.getElementById("myCanvas");
var context=myCanvas.getContext('2d');
var imagewidth=myCanvas.width;
var imageheight=myCanvas.height;
var yourCanvas=document.getElementById("yourCanvas");
var context2=yourCanvas.getContext('2d');
var image = new Image();
image.src = "haoba.jpg";
image.onload = function(){
context.drawImage(image,0,0);
var imgData=context.getImageData(50,50,200,200);
context2.putImageData(imgData,10,260);
//ctx.putImageData(imgData,200,260,50,50,100,100);
};
var ws = null;
function startServer() {
var url = "ws://192.168.137.27:8081/hao/msg";
if ('WebSocket' in window) {
ws = new WebSocket(url);
} else if ('MozWebSocket' in window) {
ws = new MozWebSocket(url);
} else {
alert('浏览器不支持');
return;
}
ws.binaryType = "arraybuffer";
ws.onopen = function() {
alert('Opened!');
};
// 收到服务器发送的文本消息, event.data表示文本内容
ws.onmessage = function(event) {
if(event.data instanceof ArrayBuffer){
var bytearray = new Uint8Array(event.data);
var tempcanvas = yourCanvas;
tempcanvas.height = imageheight;
tempcanvas.width = imagewidth;
var tempcontext = tempcanvas.getContext('2d');
var imgdata = tempcontext.getImageData(0,0,imagewidth,imageheight);
var imgdatalen = imgdata.data.length;
for(var i=8;i<imgdatalen;i++){
imgdata.data[i] = bytearray[i];
}
tempcontext.putImageData(imgdata,0,0);
var img = document.createElement('img');
img.height = imageheight;
img.width = imagewidth;
img.src = tempcanvas.toDataURL();
var chatdiv=document.getElementById("chatdiv");
chatdiv.appendChild(img);
chatdiv.innerHTML = chatdiv.innerHTML + "<br />";
}else{
alert('Receive message: ' + event.data);
}
};
ws.onclose = function() {
alert('Closed!');
}
ws.onerror = function(err){
alert(err);
};
}
//发送信息
function sendMessage(){
var textMessage=document.getElementById("textMessage").value;
if(ws!=null&&textMessage!=""){
ws.send(textMessage);
}
}
function sendphoto(){
imagedata = context.getImageData(0, 0, imagewidth,imageheight);
var canvaspixelarray = imagedata.data;
var canvaspixellen = canvaspixelarray.length;
var bytearray = new Uint8Array(canvaspixellen);
for (var i=0;i<canvaspixellen;++i) {
bytearray[i] = canvaspixelarray[i];
}
ws.send(bytearray.buffer);
context.fillStyle = '#000000';
context.fillRect(0, 0, imagewidth,imageheight);
}
</script>
</html>
tomcat7下的服务端
HelloWorldWebSocketServlet.java
package com.hao;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
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 HelloWorldWebSocketServlet extends WebSocketServlet {
public static Map<String,MyMessageInbound> mmiList = new HashMap<String,MyMessageInbound>();
protected StreamInbound createWebSocketInbound(String subProtocol,
HttpServletRequest arg1) {
return new MyMessageInbound();
}
public int getUserCount(){
return mmiList.size();
}
private class MyMessageInbound extends MessageInbound {
WsOutbound myoutbound;
String mykey;
@Override
public void onOpen(WsOutbound outbound) {
try {
System.out.println("Open Client.");
this.myoutbound = outbound;
mykey =""+System.currentTimeMillis();;
mmiList.put(mykey, this);
System.out.println("mmiList size:"+mmiList.size());
outbound.writeTextMessage(CharBuffer.wrap("open "+mykey));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onClose(int status) {
System.out.println("Close Client.");
//mmiList.remove(this);
mmiList.remove(mykey);
}
@Override
protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
System.out.println("websocket-----onBinaryMessage:"+arg0.toString());
for (Map.Entry<String, MyMessageInbound> entry : mmiList.entrySet()) {
System.out.println(entry.getKey()+"--bin---");
MyMessageInbound mmib = (MyMessageInbound) entry.getValue();
mmib.myoutbound.writeBinaryMessage(arg0);
mmib.myoutbound.flush();
}
}
@Override
protected void onTextMessage(CharBuffer message) throws IOException {
System.out.println("onText--->" + message.toString());
String[] msgarray= message.toString().split(",");
for (Map.Entry<String, MyMessageInbound> entry : mmiList.entrySet()) {
System.out.println(entry.getKey()+"-----");
MyMessageInbound mmib = (MyMessageInbound) entry.getValue();
CharBuffer buffer = CharBuffer.wrap(message);
System.out.println(buffer);
mmib.myoutbound.writeTextMessage(buffer);
mmib.myoutbound.flush();
}
}
}
}
tomcat的配置文件:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="true">
<servlet>
<servlet-name>haomsg</servlet-name>
<servlet-class>com.hao.HelloWorldWebSocketServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>haomsg</servlet-name>
<url-pattern>/hao/msg</url-pattern>
</servlet-mapping>
</web-app>