2018-04-03 11:50:50 2219瀏覽
首先給大家說一下:需要jdk7,tomcat需要支持websocket的版本,那么下面我們來看一下關(guān)于使用JavaWeb webSocket實(shí)現(xiàn)簡易的點(diǎn)對點(diǎn)聊天功能實(shí)例代碼吧。packagesocket; importjava.nio.CharBuffer; importjava.util.ArrayList; importjava.util.HashMap; importjava.util.List; importjavax.servlet.ServletConfig; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importorg.apache.catalina.websocket.MessageInbound; publicclassInitServletextendsHttpServlet{ privatestaticfinallongserialVersionUID=-L; //privatestaticList<MessageInbound>socketList; privatestaticHashMap<String,MessageInbound>socketList; publicvoidinit(ServletConfigconfig)throwsServletException{ //InitServlet.socketList=newArrayList<MessageInbound>(); InitServlet.socketList=newHashMap<String,MessageInbound>(); super.init(config); System.out.println("Serverstart============"); } publicstaticHashMap<String,MessageInbound>getSocketList(){ returnInitServlet.socketList; } /*publicstaticList<MessageInbound>getSocketList(){ returnInitServlet.socketList; } */}
packagesocket; importjava.io.IOException; importjava.io.PrintWriter; importjava.nio.CharBuffer; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importorg.apache.catalina.websocket.StreamInbound; importorg.apache.catalina.websocket.WebSocketServlet; /** * *@ClassName:MyWebSocketServlet *@Description:建立連接時創(chuàng)立 *@authormangues *@date-- */ publicclassMyWebSocketServletextendsWebSocketServlet{ publicStringgetUser(HttpServletRequestrequest){ StringuserName=(String)request.getSession().getAttribute("user"); if(userName==null){ returnnull; } returnuserName; //return(String)request.getAttribute("user"); } @Override protectedStreamInboundcreateWebSocketInbound(Stringarg, HttpServletRequestrequest){ System.out.println("##########"); returnnewMyMessageInbound(this.getUser(request)); } }
packagesocket; importjava.io.IOException; importjava.nio.ByteBuffer; importjava.nio.CharBuffer; importjava.util.HashMap; importorg.apache.catalina.websocket.MessageInbound; importorg.apache.catalina.websocket.WsOutbound; importutil.MessageUtil; publicclassMyMessageInboundextendsMessageInbound{ privateStringname; publicMyMessageInbound(){ super(); } publicMyMessageInbound(Stringname){ super(); this.name=name; } @Override protectedvoidonBinaryMessage(ByteBufferarg)throwsIOException{ //TODOAuto-generatedmethodstub } @Override protectedvoidonTextMessage(CharBuffermsg)throwsIOException{ //用戶所發(fā)消息處理后的map HashMap<String,String>messageMap=MessageUtil.getMessage(msg);//處理消息類 //上線用戶集合類map HashMap<String,MessageInbound>userMsgMap=InitServlet.getSocketList(); StringfromName=messageMap.get("fromName");//消息來自人的userId StringtoName=messageMap.get("toName");//消息發(fā)往人的userId //獲取該用戶 MessageInboundmessageInbound=userMsgMap.get(toName);//在倉庫中取出發(fā)往人的MessageInbound if(messageInbound!=null){//如果發(fā)往人存在進(jìn)行操作 WsOutboundoutbound=messageInbound.getWsOutbound(); Stringcontent=messageMap.get("content");//獲取消息內(nèi)容 StringmsgContentString=fromName+""+content;//構(gòu)造發(fā)送的消息 //發(fā)出去內(nèi)容 CharBuffertoMsg=CharBuffer.wrap(msgContentString.toCharArray()); outbound.writeTextMessage(toMsg);// outbound.flush(); } /*for(MessageInboundmessageInbound:InitServlet.getSocketList()){ CharBufferbuffer=CharBuffer.wrap(msg); WsOutboundoutbound=messageInbound.getWsOutbound(); outbound.writeTextMessage(buffer); outbound.flush(); }*/ } @Override protectedvoidonClose(intstatus){ InitServlet.getSocketList().remove(this); super.onClose(status); } @Override protectedvoidonOpen(WsOutboundoutbound){ super.onOpen(outbound); //登錄的用戶注冊進(jìn)去 if(name!=null){ InitServlet.getSocketList().put(name,this); } //InitServlet.getSocketList().add(this); } }
packageutil; importjava.nio.CharBuffer; importjava.util.HashMap; /** * *@ClassName:MessageUtil *@Description:消息處理類 *@authormangues *@date-- */ publicclassMessageUtil{ publicstaticHashMap<String,String>getMessage(CharBuffermsg){ HashMap<String,String>map=newHashMap<String,String>(); StringmsgString=msg.toString(); Stringm[]=msgString.split(","); map.put("fromName",m[]); map.put("toName",m[]); map.put("content",m[]); returnmap; } }
<?xmlversion="1.0"encoding="UTF-8"?> <web-appversion="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 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"> <servlet> <servlet-name>mywebsocket</servlet-name> <servlet-class>socket.MyWebSocketServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>mywebsocket</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet> <servlet-name>initServlet</servlet-name> <servlet-class>socket.InitServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
A.小化 <%@pagelanguage="java"contentType="text/html;charset=UTF-" pageEncoding="UTF-"%> <!DOCTYPEhtml> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=UTF-"> <title>Index</title> <scripttype="text/javascript"src="js/jquery...min.js"></script> <%session.setAttribute("user","小化");%> <scripttype="text/javascript"> varws=null; functionstartWebSocket(){ if('WebSocket'inwindow) ws=newWebSocket("ws://localhost:/webSocket/mywebsocket.do"); elseif('MozWebSocket'inwindow) ws=newMozWebSocket("ws://localhost:/webSocket/mywebsocket.do"); else alert("notsupport"); ws.onmessage=function(evt){ //alert(evt.data); console.log(evt); $("#xiaoxi").val(evt.data); }; ws.onclose=function(evt){ //alert("close"); document.getElementById('denglu').innerHTML="離線"; }; ws.onopen=function(evt){ //alert("open"); document.getElementById('denglu').innerHTML="在線"; document.getElementById('userName').innerHTML='小化'; }; } functionsendMsg(){ varfromName="小化"; vartoName=document.getElementById('name').value;//發(fā)給誰 varcontent=document.getElementById('writeMsg').value;//發(fā)送內(nèi)容 ws.send(fromName+","+toName+","+content); } </script> </head> <bodyonload="startWebSocket();"> <p>聊天功能實(shí)現(xiàn)</p> 登錄狀態(tài): <spanid="denglu"style="color:red;">正在登錄</span> <br> 登錄人: <spanid="userName"></span> <br> <br> <br> 發(fā)送給誰:<inputtype="text"id="name"value="小明"></input> <br> 發(fā)送內(nèi)容:<inputtype="text"id="writeMsg"></input> <br> 聊天框:<textarearows=""cols=""readonlyid="xiaoxi"></textarea> <br> <inputtype="button"value="send"onclick="sendMsg()"></input> </body> </html> B.小明 <%@pagelanguage="java"contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPEhtml> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"> <title>Index</title> <scripttype="text/javascript"src="js/jquery2.1.1.min.js"></script> <%session.setAttribute("user","小明");%> <scripttype="text/javascript"> varws=null; functionstartWebSocket(){ if('WebSocket'inwindow) ws=newWebSocket("ws://localhost:8080/webSocket/mywebsocket.do"); elseif('MozWebSocket'inwindow) ws=newMozWebSocket("ws://localhost:8080/webSocket/mywebsocket.do"); else alert("notsupport"); ws.onmessage=function(evt){ console.log(evt); //alert(evt.data); $("#xiaoxi").val(evt.data); }; ws.onclose=function(evt){ //alert("close"); document.getElementById('denglu').innerHTML="離線"; }; ws.onopen=function(evt){ //alert("open"); document.getElementById('denglu').innerHTML="在線"; document.getElementById('userName').innerHTML="小明"; }; } functionsendMsg(){ varfromName="小明"; vartoName=document.getElementById('name').value;//發(fā)給誰 varcontent=document.getElementById('writeMsg').value;//發(fā)送內(nèi)容 ws.send(fromName+","+toName+","+content); } </script> </head> <bodyonload="startWebSocket();"> <p>聊天功能實(shí)現(xiàn)</p> 登錄狀態(tài): <spanid="denglu"style="color:red;">正在登錄</span> <br> 登錄人: <spanid="userName"></span> <br> <br> <br> 發(fā)送給誰:<inputtype="text"id="name"value="小化"></input> <br> 發(fā)送內(nèi)容:<inputtype="text"id="writeMsg"></input> <br> 聊天框:<textarearows="13"cols="100"readonlyid="xiaoxi"></textarea> <br> <inputtype="button"value="send"onclick="sendMsg()"></input> </body> </html>以上所述是小編給大家介紹的使用JavaWebwebSocket實(shí)現(xiàn)簡易的點(diǎn)對點(diǎn)聊天功能實(shí)例代碼的相關(guān)知識,希望對大家有所幫助,最后想要了解更多Java信息的同學(xué)可以前往扣丁學(xué)堂官網(wǎng)咨詢,扣丁學(xué)堂Java培訓(xùn)深受學(xué)員的喜愛??鄱W(xué)堂不僅有專業(yè)的老師和與時俱進(jìn)的課程體系,還有大量的Java視頻教程供學(xué)員觀看學(xué)習(xí)哦。Java技術(shù)交流群:670348138。
【關(guān)注微信公眾號獲取更多學(xué)習(xí)資料】
查看更多關(guān)于“Java開發(fā)資訊”的相關(guān)文章>>