您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 广告经营 > 基于websocket和java的多人聊天室
1/8最新基于websocket与java的多人聊天室实现架构html5+websocket+javaEE7+tomcat8JavaEE7最新的websocket1.0APITomcat8开始支持websocket1.0API【TomcatimplementstheJavaWebSocket1.0APIdefinedbyJSR-356】在编写代码之前你要导入javaEE7的jar包以便使用websocketAPI,将此项目部署到tomcat8里面。具体代码如下:Java端:ChatAnnotation类;使用的是注解的方式。packagewebsocket.chat;2/8importjava.io.IOException;importjava.util.Set;importjava.util.concurrent.CopyOnWriteArraySet;importjava.util.concurrent.atomic.AtomicInteger;importjavax.websocket.OnClose;importjavax.websocket.OnError;importjavax.websocket.OnMessage;importjavax.websocket.OnOpen;importjavax.websocket.Session;importjavax.websocket.server.ServerEndpoint;importorg.apache.juli.logging.Log;importorg.apache.juli.logging.LogFactory;importutil.HTMLFilter;@ServerEndpoint(value=/websocket/chat)publicclassChatAnnotation{privatestaticfinalLoglog=LogFactory.getLog(ChatAnnotation.class);privatestaticfinalStringGUEST_PREFIX=Guest;privatestaticfinalAtomicIntegerconnectionIds=newAtomicInteger(0);privatestaticfinalSetChatAnnotationconnections=newCopyOnWriteArraySet();privatefinalStringnickname;privateSessionsession;publicChatAnnotation(){nickname=GUEST_PREFIX+connectionIds.getAndIncrement();}@OnOpenpublicvoidstart(Sessionsession){this.session=session;connections.add(this);Stringmessage=String.format(*%s%s,nickname,hasjoined.);broadcast(message);3/8}@OnClosepublicvoidend(){connections.remove(this);Stringmessage=String.format(*%s%s,nickname,hasdisconnected.);broadcast(message);}@OnMessagepublicvoidincoming(Stringmessage){//NevertrusttheclientStringfilteredMessage=String.format(%s:%s,nickname,HTMLFilter.filter(message.toString()));broadcast(filteredMessage);}@OnErrorpublicvoidonError(Throwablet)throwsThrowable{log.error(ChatError:+t.toString(),t);}privatestaticvoidbroadcast(Stringmsg){for(ChatAnnotationclient:connections){try{synchronized(client){client.session.getBasicRemote().sendText(msg);}}catch(IOExceptione){log.debug(ChatError:Failedtosendmessagetoclient,e);connections.remove(client);try{client.session.close();}catch(IOExceptione1){//Ignore}4/8Stringmessage=String.format(*%s%s,client.nickname,hasbeendisconnected.);broadcast(message);}}}}里面的juli.jar包可以百度一下自行下载。util.HTMLFilter类如下:HTMLFilter类。packageutil;/***HTMLfilterutility.**@authorCraigR.McClanahan*@authorTimTye*/publicfinalclassHTMLFilter{/***Filterthespecifiedmessagestringforcharactersthataresensitive*inHTML.ThisavoidspotentialattackscausedbyincludingJavaScript*codesintherequestURLthatisoftenreportedinerrormessages.**@parammessageThemessagestringtobefiltered*/publicstaticStringfilter(Stringmessage){if(message==null)return(null);charcontent[]=newchar[message.length()];message.getChars(0,message.length(),content,0);5/8StringBuilderresult=newStringBuilder(content.length+50);for(inti=0;icontent.length;i++){switch(content[i]){case'':result.append(<);break;case'':result.append(>);break;case'&':result.append(&);break;case'':result.append(");break;default:result.append(content[i]);}}return(result.toString());}}接下来是web端:Chat.xhtml?xmlversion=1.0encoding=UTF-8?htmlxmlns=:lang=enheadtitleApacheTomcatWebSocketExamples:Chat/titlestyletype=text/css![CDATA[input#chat{width:410px}6/8#console-container{width:400px;}#console{border:1pxsolid#CCCCCC;border-right-color:#999999;border-bottom-color:#999999;height:170px;overflow-y:scroll;padding:5px;width:100%;}#consolep{padding:0;margin:0;}]]/stylescripttype=application/javascript![CDATA[usestrict;varChat={};Chat.socket=null;Chat.connect=(function(host){if('WebSocket'inwindow){Chat.socket=newWebSocket(host);}elseif('MozWebSocket'inwindow){Chat.socket=newMozWebSocket(host);}else{Console.log('Error:WebSocketisnotsupportedbythisbrowser.');return;}Chat.socket.onopen=function(){Console.log('Info:WebSocketconnectionopened.');document.getElementById('chat').onkeydown=function(event){if(event.keyCode==13){Chat.sendMessage();}7/8};};Chat.socket.onclose=function(){document.getElementById('chat').onkeydown=null;Console.log('Info:WebSocketclosed.');};Chat.socket.onmessage=function(message){Console.log(message.data);};});Chat.initialize=function(){if(window.location.protocol=='http:'){Chat.connect('ws://'+window.location.host+'/examples/websocket/chat');}else{Chat.connect('wss://'+window.location.host+'/examples/websocket/chat');}};Chat.sendMessage=(function(){varmessage=document.getElementById('chat').value;if(message!=''){Chat.socket.send(message);document.getElementById('chat').value='';}});varConsole={};Console.log=(function(message){varconsole=document.getElementById('console');varp=document.createElement('p');p.style.wordWrap='break-word';p.innerHTML=message;console.appendChild(p);while(console.childNodes.length25){console.removeChild(console.firstChild);}console.scrollTop=console.scrollHeight;});8/8Chat.initialize();document.addEventListener(DOMContentLoaded,function(){//Removeelementswithnoscriptclass-noscriptisnotallowedinXHTMLvarnoscripts=document.getElementsByClassName(noscript);for(vari=0;inoscripts.l
本文标题:基于websocket和java的多人聊天室
链接地址:https://www.777doc.com/doc-6022851 .html