欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用JavaWeb webSocket实现简易的点对点聊天功能实例代码

程序员文章站 2024-03-11 15:08:25
首先给大家声明一点:需要 jdk 7 , tomcat需要支持websocket的版本  1.initservlet    该类主...

首先给大家声明一点:需要 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" style="color:red;">正在登录</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" style="color:red;">正在登录</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实现简易的点对点聊天功能实例代码的相关知识,希望对大家有所帮助