项目框架是别人定的,我也想使用nodeJS或者tomcat 7自带的WebSocketServlet,无奈。。
过程中碰到几个比较烦人的问题:
1、协议
2、转码
3、兼容性
对于协议和转码,我是用https://issues.apache.org/jira/browse/DIRMINA-907里面的WebSocketFilter;
对于兼容性,我是用swf代替,这里还会有个swf与java通信的问题,socket会收到<policy-file-request/>,我这里使用http://my.oschina.net/noahxiao/blog/71611的FlashPolicyServer这个类处理。
下面粘部分代码实现:
public class WebSocketServer {
public static final int PORT = 10000;
public static void main(String[] args) {
WebSocketIoHandler handler = new WebSocketIoHandler();
NioSocketAcceptor acceptor = new NioSocketAcceptor();
acceptor.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));
acceptor.getFilterChain().addLast("protocol", new ProtocolCodecFilter(new WebSocketCodecFactory()));
acceptor.setHandler(handler);
try {
acceptor.bind(new InetSocketAddress(PORT));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class WebSocketIoHandler extends IoHandlerAdapter {
<span style="white-space:pre"> </span>public static final String INDEX_KEY = WebSocketIoHandler.class.getName() + ".INDEX";
Map<Integer, List<IoSession>> videoIoSession = new HashMap<Integer, List<IoSession>>();
public void messageReceived(IoSession session, Object message) throws Exception {
IoBuffer buffer = (IoBuffer)message;
byte[] b = new byte[buffer.limit()];
buffer.get(b);
String code = new String(b, "utf-8");
// System.out.println(code);
if(code == null || code.equals("")){
return ;
}
//105100 --->videoId
if(code.startsWith("videoid")){
int videoId = 0;
try {
String id = code.substring(7);
// System.out.println("------------videoid"+id);
videoId = Integer.valueOf(id);
} catch (Exception e) {
return ;
}
if(videoId <= 0){
return ;
}
ioSessionIsIn