websocket传传图片

参考[url]http://www.adobe.com/devnet/archive/html5/articles/real-time-data-exchange-in-html5-with-websockets.html
[/url]
server端还是用tomcat7的方式
客户端





Insert title here



myCanvas
yourCanvas
chatdiv










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 mmiList = new HashMap();

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 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 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的配置文件:


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">

haomsg
com.hao.HelloWorldWebSocketServlet


haomsg
/hao/msg


你可能感兴趣的:(websocket,javascript)