欧美成人午夜免费全部完,亚洲午夜福利精品久久,а√最新版在线天堂,另类亚洲综合区图片小说区,亚洲欧美日韩精品色xxx

使用JavaWeb webSocket實(shí)現(xiàn)簡易的點(diǎn)對點(diǎn)聊天功能實(shí)例代碼

2018-04-03 11:50:50 2219瀏覽

首先給大家說一下:需要jdk7,tomcat需要支持websocket的版本,那么下面我們來看一下關(guān)于使用JavaWeb webSocket實(shí)現(xiàn)簡易的點(diǎn)對點(diǎn)聊天功能實(shí)例代碼吧。


1、InitServlet

該類主要是用來初始化構(gòu)造將來存儲用戶身份信息的map倉庫,利用其初始化方法Init初始化倉庫,利用其靜態(tài)方法getSocketList獲得對應(yīng)的用戶身份信息。

webSocket,我認(rèn)為MessageInbound用來識別登錄人的信息,用它來找到對應(yīng)的人,推送消息。每次登錄都會產(chǎn)生一個MessageInbound。

這里的HashMap<String,MessageInbound>:string存儲用戶session的登錄id,MessageInbound存儲推送需要的身份信息。以上屬于個人口頭話理解。

  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;
  }
  */}

2、MyWebSocketServlet

websocket用來建立連接的servlet,建立連接時,首先在session獲取該登錄人的userId,在調(diào)用MyMessageInbound構(gòu)造函數(shù)傳入userId


  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));
  }
  }


3、onOpen方法調(diào)用InitServlet的map身份倉庫

放入用戶userId和對應(yīng)該登錄用戶的websocket身份信息MessageInbound(可以用userId來尋找到推送需要的身份MessageInbound)

onTextMessage:用來獲取消息,并發(fā)送消息

  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);
  }
  }

4、消息處理類,處理前端發(fā)來的消息

  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;
  }
  }

5、web配置


  <?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>


6、前端,為方便起見,我直接用了兩個jsp,在其中用<%session.setAttribute("user","小明")%>;來表示登錄。

兩個jsp沒任何本質(zhì)差別,只是用來表示兩個不同的人登錄,可以同兩個瀏覽器打開不同的jsp,來聊天操作

  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)注微信公眾號獲取更多學(xué)習(xí)資料



查看更多關(guān)于“Java開發(fā)資訊的相關(guān)文章>>

標(biāo)簽: JavaEE視頻教程 JavaEE培訓(xùn) JavaEE開發(fā)工程師 Java培訓(xùn) Java開發(fā)程序員 Java面試題

熱門專區(qū)

暫無熱門資訊

課程推薦

微信
微博
15311698296

全國免費(fèi)咨詢熱線

郵箱:codingke@1000phone.com

官方群:148715490

北京千鋒互聯(lián)科技有限公司版權(quán)所有   北京市海淀區(qū)寶盛北里西區(qū)28號中關(guān)村智誠科創(chuàng)大廈4層
京ICP備2021002079號-2   Copyright ? 2017 - 2022
返回頂部 返回頂部