久久ER99热精品一区二区-久久精品99国产精品日本-久久精品免费一区二区三区-久久综合九色综合欧美狠狠

專欄中心

EEPW首頁 > 專欄 > 扣丁學(xué)堂Java培訓(xùn)之webSocket實現(xiàn)簡易的點對點聊天功能分享

扣丁學(xué)堂Java培訓(xùn)之webSocket實現(xiàn)簡易的點對點聊天功能分享

發(fā)布人:扣丁客 時間:2020-12-09 來源:工程師 發(fā)布文章

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

1、InitServlet

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

webSocket,我認為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ā)往人存在進行操作
  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);
  //登錄的用戶注冊進去
  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>聊天功能實現(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>聊天功能實現(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實現(xiàn)簡易的點對點聊天功能實例代碼的相關(guān)知識,希望對大家有所幫助,最后想要了解更多Java信息的同學(xué)可以前往扣丁學(xué)堂官網(wǎng)咨詢,扣丁學(xué)堂Java培訓(xùn)深受學(xué)員的喜愛。扣丁學(xué)堂不僅有專業(yè)的老師和與時俱進的課程體系,還有大量的Java視頻教程供學(xué)員觀看學(xué)習(xí)哦。扣丁學(xué)堂java技術(shù)交流群:487098661。

*博客內(nèi)容為網(wǎng)友個人發(fā)布,僅代表博主個人觀點,如有侵權(quán)請聯(lián)系工作人員刪除。

關(guān)鍵詞:

相關(guān)推薦

研華COM-HPC Size C模塊SOM-C350,助力存儲ATE測試設(shè)備快速部署

貿(mào)澤電子開售能為電動汽車牽引逆變器提供可擴展性能的英飛凌HybridPACK Drive G2模塊

Littelfuse推出高性能超級結(jié)X4-Class 200V功率MOSFET

Intersil公司2010年路演武漢站講座6--無線基礎(chǔ)設(shè)施應(yīng)用解決方案

視頻 2011-10-18

Vishay推出采用eSMP系列SMF(DO-219AB)封裝的全新1A和2A Gen 7 1200V FRED Pt超快恢復(fù)整流器

芯科科技率先支持Matter 1.4,推動智能家居邁向新高度

Intersil公司2010年路演武漢站講座2--ISim設(shè)計工具

德州儀器新型MCU可實現(xiàn)邊緣AI和先進的實時控制

UPS逆變器數(shù)字化控制技術(shù)

Intersil公司2010年路演武漢站講座3--高速有源有線 & 顯示端口

uvision2 調(diào)試命令 pdf

資源下載 2007-02-16

Intersil公司2010年路演武漢站講座1--通信電源解決方案

視頻 2011-10-18

研華全新模塊化電腦SOM-6833助力5G路測設(shè)備升級

ULN2003A-高壓大電流達林頓晶體管陣列系列產(chǎn)品及其應(yīng)用

利用自助服務(wù)軟件許可為設(shè)計師賦權(quán)

Intersil公司2010年路演武漢站講座4--用于儀器及工業(yè)應(yīng)用的高性能模擬信號鏈產(chǎn)品

視頻 2011-10-18

Uedit32

瑞薩推出高性能四核應(yīng)用處理器,增強工業(yè)以太網(wǎng)與多軸電機控制解決方案陣容

射頻系統(tǒng)調(diào)制技術(shù)介紹

更多 培訓(xùn)課堂
更多 焦點
更多 視頻

技術(shù)專區(qū)