websocket的前台这里就不多说了主要说一下后台的业务逻辑。

以下是本人的websocket协议解析,框架是基于mina+spring做的。

需要的minajar包有

mina-core-2.0.4.jar

mina-integration-beans-2.0.4.jar

mina-integration-jmx-2.0.4.jar

mina-integration-ognl-2.0.4.jar

mina-integration-spring-1.1.7.jar.zip

大家还没搞出来的可以参照一下,若不对的还希望各位大神指出或者线下交流QQ:593040793

importjava.io.UnsupportedEncodingException;

importjava.security.MessageDigest;

importjava.util.HashMap;

importjava.util.Map;

importjava.util.regex.Matcher;

importjava.util.regex.Pattern;

importorg.apache.mina.core.buffer.IoBuffer;

importorg.apache.mina.core.service.IoHandlerAdapter;

importorg.apache.mina.core.session.IoSession;

importorg.codehaus.jackson.map.ObjectMapper;

importorg.springframework.beans.factory.annotation.Autowired;

importqq.web.model.Data;

importqq.web.service.MessageData;

importqq.web.service.UserService;

/**

*

*@author程欣伟

*

*/

publicclassWebSocketIoHandlerextendsIoHandlerAdapter{

@AutowiredprivateMessageDatamessageData;

@AutowiredprivateUserServiceuserService;

publicstaticfinalStringINDEX_KEY=WebSocketIoHandler.class.getName()+".INDEX";

//key=sessionIdvalue=sessionsid和session对应

privateMap<Long,IoSession>ioSessionMap=newHashMap<Long,IoSession>();

//key=userIdvalue=sessionId用户和sid对应

privateMap<Integer,Long>userSessionMap=newHashMap<Integer,Long>();

/**

*将IoBuffer转换成string

*@author程欣伟

*@parammessage

*@return

*/

publicStringioBufferToString(Objectmessage){

if(!(messageinstanceofIoBuffer)){

return"";

}

IoBufferioBuffer=(IoBuffer)message;

returnnewString(ioBuffer.array());

}

/**

*当有请求消息时触发

*@author程欣伟

*@return

*/

@Override

publicvoidmessageReceived(IoSessionsession,Objectmessage)throwsException{

//System.out.println(ioBufferToString(message));

//吧传入的消息转换成流

IoBufferbuffer=(IoBuffer)message;

//转换成字节数组

byte[]b=newbyte[buffer.limit()];

buffer.get(b);

//获取sessionId

Longsid=session.getId();

//如果没有此sessionId则代表第一次连接

if(!ioSessionMap.containsKey(sid)){

//把此session放入map

ioSessionMap.put(sid,session);

byte[]bufferAry=buffer.array();

Stringm=newString(bufferAry);

//获取握手协议字符串

Stringsss=getSecWebSocketAccept(m);

buffer.clear();

buffer.put(sss.getBytes("utf-8"));

buffer.flip();

session.write(buffer);

buffer.free();

}else{

//存在session

//解析传输的数据内容

Stringstr=decode(b);

//System.out.println(roleStr);

//---------------业务开始----------------//

ObjectMapperobjectMapper=newObjectMapper();

Datadata=null;

try{

data=objectMapper.readValue(str,Data.class);

}catch(Exceptione){

return;

}

try{

if(data.getDataType().equals("message")){

messageData.processMessage(data.getData());

}elseif(data.getDataType().equals("login")){

userService.processUser(data.getData(),sid);

}

}catch(Exceptione){

//如果处理消息报错则告知浏览器

e.printStackTrace();

data.setData("false");

sendMessageToHtml(objectMapper.writeValueAsString(data),sid);

}

}

}

/**

*发送消息给浏览器

*@author程欣伟

*@parammsg

*@paramsid

*@return

*/

publicbooleansendMessageToHtml(Stringmsg,Longsid){

booleansendFlag=true;

try{

//获取字节数组

byte[]bb=encode(msg);

//创建IO流

IoBufferioBuffer=IoBuffer.allocate(bb.length);

//把字节数组写入流中

ioBuffer.put(bb);

//api解释为翻转但是目前不知道什么意思

ioBuffer.flip();

//同步块

synchronized(ioSessionMap){

//获取所有的session

IoSessionioSession=ioSessionMap.get(sid);

if(ioSession!=null&&ioSession.isConnected()){

//复制一个新的buffer

IoBufferwriteResult=ioBuffer.duplicate();

ioSession.write(writeResult);

}else{

sendFlag=false;

}

}

ioBuffer.free();

}catch(Exceptione){

e.printStackTrace();

sendFlag=false;

}

returnsendFlag;

}

@Override

publicvoidsessionOpened(IoSessionsession)throwsException{

session.setAttribute(INDEX_KEY,0);

}

//@Override

//publicvoidsessionIdle(IoSessionsession,IdleStatusstatus)throwsException{

//System.out.println("IDLE"+session.getIdleCount(status));

//}

/**

*当ws连接断开时触发

*/

@Override

publicvoidsessionClosed(IoSessionsession)throwsException{

//如果不连接的话则删除

ioSessionMap.remove(session);;

}

/**

*根据用户ID获取session连接

*@paramuserId

*@return

*/

publicIoSessiongetSessionByUserId(intuserId){

Longsid=userSessionMap.get(userId);

if(sid==null){

returnnull;

}

IoSessionsession=ioSessionMap.get(sid);

if(session==null){

userSessionMap.remove(userId);

returnnull;

}

returnsession;

}

/**

*

*@author程欣伟

*获取握手协议字符串

*首先要获取到请求头中的Sec-WebSocket-Key的值,再把这一段GUID"258EAFA5-E914-47DA-95CA-C5AB0DC85B11

*加到获取到的Sec-WebSocket-Key的值的后面,然后拿这个字符串做SHA-1hash计算,然后再把得到的结果通过base64加密

*@paramkey

*@return

*/

privateStringgetSecWebSocketAccept(Stringkey){

StringsecKey=getSecWebSocketKey(key);

Stringguid="258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

secKey+=guid;

try{

MessageDigestmd=MessageDigest.getInstance("SHA-1");

md.update(secKey.getBytes("iso-8859-1"),0,secKey.length());

byte[]sha1Hash=md.digest();

secKey=base64Encode(sha1Hash);

}catch(Exceptione){

e.printStackTrace();

}

Stringrtn="HTTP/1.1101SwitchingProtocols\r\nUpgrade:websocket\r\nConnection:Upgrade\r\nSec-WebSocket-Accept:"

+secKey+"\r\n\r\n";

returnrtn;

}

/**

*

*@author程欣伟

*获取到请求头中的Sec-WebSocket-Key的

*@paramreq

*@return

*/

privateStringgetSecWebSocketKey(Stringreq){

Patternp=Pattern.compile("^(Sec-WebSocket-Key:).+",

Pattern.CASE_INSENSITIVE|Pattern.MULTILINE);

Matcherm=p.matcher(req);

if(m.find()){

Stringfoundstring=m.group();

returnfoundstring.split(":")[1].trim();

}else{

returnnull;

}

}

/**

*base64

*@paraminput

*@return

*/

privateStringbase64Encode(byte[]input){

returnnewString(org.apache.mina.util.Base64.encodeBase64(input));

}

/**

*@author程欣伟

*把传入的消息解码

*@paramreceivedDataBuffer

*@return

*@throwsUnsupportedEncodingException

*/

privateStringdecode(byte[]receivedDataBuffer)

throwsUnsupportedEncodingException{

Stringresult=null;

//数据开始的位数前面2个byte固定必须存在

intdataStartIndex=2;

//查看第一帧的值代表是否结束

intisend=receivedDataBuffer[0]>>7&0x1;

System.out.println("是否结束:【"+(isend==1?"yes":"no")+"】");

//获取是否需要掩码

booleanmask=((receivedDataBuffer[1]>>7&0x1)==1)?true:false;

System.out.println("掩码:【"+(mask?"yes":"no")+"】");

//Payloadlength:传输数据的长度,以字节的形式表示:7位、7+16位、或者7+64位。

//如果这个值以字节表示是0-125这个范围,那这个值就表示传输数据的长度;

//如果这个值是126,则随后的两个字节表示的是一个16进制无符号数,用来表示传输数据的长度;

//如果这个值是127,则随后的是8个字节表示的一个64位无符合数,这个数用来表示传输数据的长度

intdataLength=receivedDataBuffer[1]&0x7F;

System.out.println("描述消息长度:【"+dataLength+"】");

//查看消息描述是否大于126如果大于

if(dataLength<126){

//126以内取本身

}elseif(dataLength==126){

dataStartIndex=dataStartIndex+2;

}elseif(dataLength==127){

dataStartIndex=dataStartIndex+8;

}

//掩码数组

byte[]frameMaskingAry=newbyte[4];

if(mask){

for(inti=0;i<frameMaskingAry.length;i++){

frameMaskingAry[i]=receivedDataBuffer[dataStartIndex+i];

}

dataStartIndex+=4;

}

//计算非空位置

intlastStation=receivedDataBuffer.length-1;

//利用掩码对org-data进行异或

intframe_masking_key=0;

//保存数据的数组

byte[]dataByte=newbyte[lastStation-dataStartIndex+1];

if(mask){

for(inti=dataStartIndex;i<=lastStation;i++){

//吧数据进行异或运算

receivedDataBuffer[i]=(byte)(receivedDataBuffer[i]^frameMaskingAry[frame_masking_key%4]);

//吧进行异或运算之后的数据放入数组

dataByte[i-dataStartIndex]=receivedDataBuffer[i];

frame_masking_key++;

}

}

result=newString(dataByte,"UTF-8");

System.out.println(result);

returnresult;

}

/**

*@author程欣伟

*对传入数据进行无掩码转换

*@parammsg

*@return

*@throwsUnsupportedEncodingException

*/

privatebyte[]encode(Stringmsg)throwsUnsupportedEncodingException{

//掩码开始位置

intmasking_key_startIndex=2;

byte[]msgByte=msg.getBytes("UTF-8");

//计算掩码开始位置

if(msgByte.length<=125){

masking_key_startIndex=2;

}elseif(msgByte.length>65536){

masking_key_startIndex=10;

}elseif(msgByte.length>125){

masking_key_startIndex=4;

}

//创建返回数据

byte[]result=newbyte[msgByte.length+masking_key_startIndex];

//开始计算ws-frame

//frame-fin+frame-rsv1+frame-rsv2+frame-rsv3+frame-opcode

result[0]=(byte)0x81;//129

//frame-masked+frame-payload-length

//从第9个字节开始是1111101=125,掩码是第3-第6个数据

//从第9个字节开始是1111110>=126,掩码是第5-第8个数据

if(msgByte.length<=125){

result[1]=(byte)(msgByte.length);

}elseif(msgByte.length>65536){

result[1]=0x7F;//127

}elseif(msgByte.length>125){

result[1]=0x7E;//126

result[2]=(byte)(msgByte.length>>;

result[3]=(byte)(msgByte.length%256);

}

//将数据编码放到最后

for(inti=0;i<msgByte.length;i++){

result[i+masking_key_startIndex]=msgByte[i];

}

decode(result);

Stringstr=newString(result,"utf-8");

System.out.println(str);

returnresult;

}

publicMap<Long,IoSession>getIoSessionMap(){

returnioSessionMap;

}

publicvoidsetIoSessionMap(Map<Long,IoSession>ioSessionMap){

this.ioSessionMap=ioSessionMap;

}

publicMap<Integer,Long>getUserSessionMap(){

returnuserSessionMap;

}

publicvoidsetUserSessionMap(Map<Integer,Long>userSessionMap){

this.userSessionMap=userSessionMap;

}

publicstaticvoidmain(String[]args)throwsUnsupportedEncodingException{

byteb=8;

System.out.println(""

+(byte)((b>>7)&0x1)+(byte)((b>>6)&0x1)

+(byte)((b>>5)&0x1)+(byte)((b>>4)&0x1)

+(byte)((b>>3)&0x1)+(byte)((b>>2)&0x1)

+(byte)((b>>1)&0x1)+(byte)((b>>0)&0x1)

);

byte[]a={(byte)104,(byte)49};

System.out.println(newString(a,"utf-8"));

}

}