一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務(wù)器之家 - 編程語言 - JAVA教程 - 使用JavaWeb webSocket實現(xiàn)簡易的點對點聊天功能實例代碼

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

2020-04-30 09:51mangues JAVA教程

這篇文章主要介紹了使用JavaWeb webSocket實現(xiàn)簡易的點對點聊天功能實例代碼的相關(guān)資料,內(nèi)容介紹的非常詳細(xì),具有參考借鑒價值,感興趣的朋友一起學(xué)習(xí)吧

首先給大家聲明一點:需要 jdk 7 , tomcat需要支持websocket的版本 

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存儲 推送需要的身份信息。以上屬于個人口頭話理解。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package socket;
 import java.nio.CharBuffer;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import javax.servlet.ServletConfig;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import org.apache.catalina.websocket.MessageInbound;
 public class InitServlet extends HttpServlet {
   private static final long serialVersionUID = -L;
   //private static List<MessageInbound> socketList; 
   private static HashMap<String,MessageInbound> socketList; 
   public void init(ServletConfig config) throws ServletException { 
 //    InitServlet.socketList = new ArrayList<MessageInbound>(); 
     InitServlet.socketList = new HashMap<String,MessageInbound>(); 
     super.init(config); 
     System.out.println("Server start============"); 
   
   public static HashMap<String,MessageInbound> getSocketList() { 
     return InitServlet.socketList; 
   
 /*  public static List<MessageInbound> getSocketList() { 
     return InitServlet.socketList; 
   
 */}

2.MyWebSocketServlet 

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package socket;
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.nio.CharBuffer;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import org.apache.catalina.websocket.StreamInbound;
 import org.apache.catalina.websocket.WebSocketServlet;
 /**
 *
 * @ClassName: MyWebSocketServlet
 * @Description: 建立連接時創(chuàng)立
 * @author mangues
 * @date --
 */
 public class MyWebSocketServlet extends WebSocketServlet {
   public String getUser(HttpServletRequest request){
     String userName = (String) request.getSession().getAttribute("user");
     if(userName==null){
       return null;
     }
     return userName;
    // return (String) request.getAttribute("user");
   }
   @Override
   protected StreamInbound createWebSocketInbound(String arg,
       HttpServletRequest request) {
     System.out.println("##########");
     return new MyMessageInbound(this.getUser(request));
   }
 }

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package socket;
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.nio.CharBuffer;
 import java.util.HashMap;
 import org.apache.catalina.websocket.MessageInbound;
 import org.apache.catalina.websocket.WsOutbound;
 import util.MessageUtil;
 public class MyMessageInbound extends MessageInbound {
   private String name;
   public MyMessageInbound() {
     super();
   }
   public MyMessageInbound(String name) {
     super();
     this.name = name;
   }
   @Override
   protected void onBinaryMessage(ByteBuffer arg) throws IOException {
     // TODO Auto-generated method stub
   }
   @Override
   protected void onTextMessage(CharBuffer msg) throws IOException {
     //用戶所發(fā)消息處理后的map
     HashMap<String,String> messageMap = MessageUtil.getMessage(msg);  //處理消息類
     //上線用戶集合類map
     HashMap<String, MessageInbound> userMsgMap = InitServlet.getSocketList();
     String fromName = messageMap.get("fromName");  //消息來自人 的userId
     String toName = messageMap.get("toName");     //消息發(fā)往人的 userId
     //獲取該用戶
     MessageInbound messageInbound = userMsgMap.get(toName);  //在倉庫中取出發(fā)往人的MessageInbound
     if(messageInbound!=null){   //如果發(fā)往人 存在進(jìn)行操作
       WsOutbound outbound = messageInbound.getWsOutbound();
       String content = messageMap.get("content"); //獲取消息內(nèi)容
       String msgContentString = fromName + "   " + content;  //構(gòu)造發(fā)送的消息
       //發(fā)出去內(nèi)容
       CharBuffer toMsg = CharBuffer.wrap(msgContentString.toCharArray());
       outbound.writeTextMessage(toMsg); //
       outbound.flush();
     }
    /* for (MessageInbound messageInbound : InitServlet.getSocketList()) {
       CharBuffer buffer = CharBuffer.wrap(msg);
       WsOutbound outbound = messageInbound.getWsOutbound();
       outbound.writeTextMessage(buffer);
       outbound.flush();
     } */
   }
   @Override
   protected void onClose(int status) {
     InitServlet.getSocketList().remove(this);
     super.onClose(status);
   }
   @Override
   protected void onOpen(WsOutbound outbound) {
     super.onOpen(outbound);
     //登錄的用戶注冊進(jìn)去
     if(name!=null){
       InitServlet.getSocketList().put(name, this);
     }
 //    InitServlet.getSocketList().add(this);
   }
 }

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package util;
import java.nio.CharBuffer;
import java.util.HashMap;
/**
 *
 * @ClassName: MessageUtil
 * @Description: 消息處理類
 * @author mangues
* @date --
*/
public class MessageUtil {
  public static HashMap<String,String> getMessage(CharBuffer msg) {
    HashMap<String,String> map = new HashMap<String,String>();
    String msgString = msg.toString();
    String m[] = msgString.split(",");
    map.put("fromName", m[]);
    map.put("toName", m[]);
    map.put("content", m[]);
    return map;
  }
}

5.web配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="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.小化

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<%@ page language="java" contentType="text/html; charset=UTF-"
   pageEncoding="UTF-"%>
 <!DOCTYPE html>
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-">
 <title>Index</title>
 <script type="text/javascript" src="js/jquery ...min.js"></script>
 <%session.setAttribute("user", "小化");%>
 <script type="text/javascript">
 var ws = null;
 function startWebSocket() {
   if ('WebSocket' in window)
     ws = new WebSocket("ws://localhost:/webSocket/mywebsocket.do");
   else if ('MozWebSocket' in window)
     ws = new MozWebSocket("ws://localhost:/webSocket/mywebsocket.do");
   else
     alert("not support");
   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='小化';
   };
 }
 function sendMsg() {
   var fromName = "小化";
   var toName = document.getElementById('name').value; //發(fā)給誰
   var content = document.getElementById('writeMsg').value; //發(fā)送內(nèi)容
   ws.send(fromName+","+toName+","+content);
 }
 </script>
 </head>
 <body onload="startWebSocket();">
 <p>聊天功能實現(xiàn)</p>
 登錄狀態(tài):
 <span id="denglu" style="color:red;">正在登錄</span>
 <br>
 登錄人:
 <span id="userName"></span>
 <br>
 <br>
 <br>
 發(fā)送給誰:<input type="text" id="name" value="小明"></input>
 <br>
 發(fā)送內(nèi)容:<input type="text" id="writeMsg"></input>
 <br>
 聊天框:<textarea rows="" cols="" readonly id="xiaoxi"></textarea>
 <br>
 <input type="button" value="send" onclick="sendMsg()"></input>
 </body>
 </html>

 B.小明

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index</title>
<script type="text/javascript" src="js/jquery 2.1.1.min.js"></script>
<%session.setAttribute("user", "小明");%>
<script type="text/javascript">
var ws = null;
function startWebSocket() {
  if ('WebSocket' in window)
    ws = new WebSocket("ws://localhost:8080/webSocket/mywebsocket.do");
  else if ('MozWebSocket' in window)
    ws = new MozWebSocket("ws://localhost:8080/webSocket/mywebsocket.do");
  else
    alert("not support");
  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="小明";
  };
}
function sendMsg() {
  var fromName = "小明";
  var toName = document.getElementById('name').value; //發(fā)給誰
  var content = document.getElementById('writeMsg').value; //發(fā)送內(nèi)容
  ws.send(fromName+","+toName+","+content);
}
</script>
</head>
<body onload="startWebSocket();">
<p>聊天功能實現(xiàn)</p>
登錄狀態(tài):
<span id="denglu" style="color:red;">正在登錄</span>
<br>
登錄人:
<span id="userName"></span>
<br>
<br>
<br>
發(fā)送給誰:<input type="text" id="name" value="小化"></input>
<br>
發(fā)送內(nèi)容:<input type="text" id="writeMsg"></input>
<br>
聊天框:<textarea rows="13" cols="100" readonly id="xiaoxi"></textarea>
<br>
<input type="button" value="send" onclick="sendMsg()"></input>
</body>
</html>

以上所述是小編給大家介紹的使用JavaWeb webSocket實現(xiàn)簡易的點對點聊天功能實例代碼的相關(guān)知識,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 236宅宅2021最新理论 | 天天综合色天天综合色sb | 精品视频一区二区三区 | 亚洲国产AV一区二区三区四区 | 欧美日韩国产一区二区三区欧 | 美国雪白人妖sarina | 国产成人高清精品免费5388密 | 513热点网| 精品午夜寂寞黄网站在线 | 亚州在线 | 日韩影院在线观看 | 性的张力| 我和岳偷长篇小说 | 操穴片| 99久久综合 | 国产亚洲女人久久久久久 | 4455永久在线观免费看片 | 国产馆| 久久精品国产在热亚洲完整版 | 亚洲狠狠综合久久 | 国内精品视频一区二区三区 | 四虎永久在线精品国产 | 免费高清www动漫视频播放器 | 亚洲成人网在线 | 国产日韩欧美精品在线 | 99久久久无码国产精品 | 2021最新国产成人精品视频 | 亚洲成色WWW久久网站夜月 | 免费精品在线视频 | 精品国产欧美一区二区 | 大胸被c出奶水嗷嗷叫 | 扒开大腿狠狠挺进视频 | 国模丰满美女冰漪34d | 动漫精品一区二区三区3d | japanesemoms乱熟| 国产乱码一卡二卡3卡四卡 国产乱插 | 亚洲香蕉伊在人在线观婷婷 | 成年视频在线播放 | 色先锋影音先锋 | 久久视频在线视频观看天天看视频 | 春意影院午夜爽爽爽免费 |