程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 應用JavaWeb webSocket完成簡略單純的點對點聊天功效實例代碼

應用JavaWeb webSocket完成簡略單純的點對點聊天功效實例代碼

編輯:關於JAVA

應用JavaWeb webSocket完成簡略單純的點對點聊天功效實例代碼。本站提示廣大學習愛好者:(應用JavaWeb webSocket完成簡略單純的點對點聊天功效實例代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是應用JavaWeb webSocket完成簡略單純的點對點聊天功效實例代碼正文


起首給年夜門風明一點:須要 jdk 7 , tomcat須要支撐websocket的版本 

1.InitServlet

   該類重要是用來初始化結構未來存儲用戶身份信息的map倉庫,應用其初始化辦法Init 初始化倉庫, 應用其靜態辦法getSocketList 取得對應的用戶身份信息。

   webSocket ,我以為MessageInbound 用來辨認登錄人的信息,用它來找到對應的人,推送新聞。每次登錄都邑發生一個MessageInbound。

  這裡的 HashMap<String,MessageInbound>    :string 存儲用戶session的登錄id,MessageInbound存儲 推送須要的身份信息。以上屬於小我行動話懂得。

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,在挪用MyMessageInbound結構函數傳入userId

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: 樹立銜接時創建 
 * @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辦法挪用InitServlet的map身份倉庫,

放入用戶userId 和 對應當登錄用戶的websocket身份信息MessageInbound (可以用userId來尋覓到推送須要的 身份MessageInbound )

 onTextMessage :用來獲得新聞,並發送新聞

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 { 
     //用戶所發新聞處置後的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");     //新聞發往人的 userId
     //獲得該用戶
     MessageInbound messageInbound = userMsgMap.get(toName);  //在倉庫中掏出發往人的MessageInbound
     if(messageInbound!=null){   //假如發往人 存在停止操作
       WsOutbound outbound = messageInbound.getWsOutbound(); 
       String content = messageMap.get("content"); //獲得新聞內容
       String msgContentString = fromName + "   " + content;  //結構發送的新聞
       //收回去內容
       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); 
     //登錄的用戶注冊出來
     if(name!=null){
       InitServlet.getSocketList().put(name, this); 
     }
 //    InitServlet.getSocketList().add(this); 
   } 
 }

4.新聞處置類,處置前端發來的新聞

 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設置裝備擺設

<?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沒任何實質差異,只是用來表現兩個分歧的人登錄,可以同兩個閱讀器翻開分歧的jsp,來聊天操作

   A.小化

<%@ 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; //發給誰
   var content = document.getElementById('writeMsg').value; //發送內容
   ws.send(fromName+","+toName+","+content);
 }
 </script>
 </head>
 <body onload="startWebSocket();">
 <p>聊天功效完成</p>
 登錄狀況:
 <span id="denglu" >正在登錄</span>
 <br>
 登錄人:
 <span id="userName"></span>
 <br>
 <br>
 <br>
 發送給誰:<input type="text" id="name" value="小明"></input>
 <br>
 發送內容:<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.小明

<%@ 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; //發給誰
  var content = document.getElementById('writeMsg').value; //發送內容
  ws.send(fromName+","+toName+","+content);
}
</script>
</head>
<body onload="startWebSocket();">
<p>聊天功效完成</p>
登錄狀況:
<span id="denglu" >正在登錄</span>
<br>
登錄人:
<span id="userName"></span>
<br>
<br>
<br>
發送給誰:<input type="text" id="name" value="小化"></input>
<br>
發送內容:<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完成簡略單純的點對點聊天功效實例代碼的相干常識,願望對年夜家有所贊助,假如年夜家有任何疑問請給我留言,小編會實時答復年夜家的。在此也異常感激年夜家對網站的支撐!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved