HTML5 WebSocket开发


需要:支持websocket的服务器,支持HTML5的浏览器,jar包

我用tomcat7+chrome22运行,注意不是所有tomcat 7都支持websocket

首先要明白websocket的流程

登录---》js提交信息--》servlet接受,返回给XX--》JS接受

于是至少需要一个链接队列,一个servlet

1.建立一个队列List<MessageInbound> socket,静态也好,缓存也好,反正记录好链接注册

2.servlet

package servlet;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;

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;

import function.Server;

final public class WebSocket extends WebSocketServlet {
 private static final long serialVersionUID = 1L;

 @Override
 protected StreamInbound createWebSocketInbound(String arg0,HttpServletRequest arg1) {
  return new SocketMessage();//新链接
 }
}
class SocketMessage extends MessageInbound {
 //重写连接
 protected void onOpen(WsOutbound outbound) {
  super.onOpen(outbound);
  Server.socket.add(this);//增加到链接队列
 }
 //重写退出
 protected void onClose(int status) {
  Server.socket.remove(this);//从链接队列删除
  super.onClose(status);
 }
 //重写数据交换 这里不同参数重构不同方法
 protected void onBinaryMessage(ByteBuffer msg) throws IOException {
 }
 protected void onTextMessage(CharBuffer msg) throws IOException {
  for (MessageInbound messageInbound : Server.socket) {//发给每个人,这个地方只有发挥,可以做到指定发送
   CharBuffer buffer = CharBuffer.wrap(msg);
   WsOutbound outbound = messageInbound.getWsOutbound();
   outbound.writeTextMessage(buffer);
   outbound.flush();
  }
 }
}

这里会发现缺少jar,导入Apache Software Foundation\Tomcat 7.0\lib里的catalina.jar和tomcat-coyote.jar即可,注意导入方式,不然部署的时候会jar冲突,因为tomcat本身就有这个2个jar

记得写入web.xml

3.写js调用

var ws;
function init() {
 if(window.WebSocket)
  ws = new WebSocket("ws://127.0.0.1:8888/ws/websocket");//上边servlet在web.xml注册的路径
 else{
  alert("不支持");
  return;
 }
 ws.onmessage = function(evt) {
  //evt.data是返回的消息
 };
 ws.onclose = function(evt) {
  //服务器关闭
 };
 ws.onopen = function(evt) {
  //连接成功
 };
}
function sendMsg() {
 //ws.send(str);//发送消息
}

注意,init()需要调用一次

相关内容