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

java 实现websocket的两种方式实例详解

程序员文章站 2024-02-22 23:48:22
一、介绍 1.两种方式,一种使用tomcat的websocket实现,一种使用spring的websocket 2.tomcat的方式需要tomcat 7.x,jee7...

一、介绍

1.两种方式,一种使用tomcat的websocket实现,一种使用spring的websocket

2.tomcat的方式需要tomcat 7.x,jee7的支持。

3.spring与websocket整合需要spring 4.x,并且使用了socketjs,对不支持websocket的浏览器可以模拟websocket使用

二、方式一:tomcat

使用这种方式无需别的任何配置,只需服务端一个处理类,

 服务器端代码

package com.socket; 
import java.io.ioexception; 
import java.util.map; 
import java.util.concurrent.concurrenthashmap; 
import javax.websocket.*; 
import javax.websocket.server.pathparam; 
import javax.websocket.server.serverendpoint; 
import net.sf.json.jsonobject; 
@serverendpoint("/websocket/{username}") 
public class websocket { 
 private static int onlinecount = 0; 
 private static map<string, websocket> clients = new concurrenthashmap<string, websocket>(); 
 private session session; 
 private string username; 
 @onopen 
 public void onopen(@pathparam("username") string username, session session) throws ioexception { 
  this.username = username; 
  this.session = session; 
  addonlinecount(); 
  clients.put(username, this); 
  system.out.println("已连接"); 
 } 
 @onclose 
 public void onclose() throws ioexception { 
  clients.remove(username); 
  subonlinecount(); 
 } 
 @onmessage 
 public void onmessage(string message) throws ioexception { 
  jsonobject jsonto = jsonobject.fromobject(message); 
  if (!jsonto.get("to").equals("all")){ 
   sendmessageto("给一个人", jsonto.get("to").tostring()); 
  }else{ 
   sendmessageall("给所有人"); 
  } 
 } 
 @onerror 
 public void onerror(session session, throwable error) { 
  error.printstacktrace(); 
 } 
 public void sendmessageto(string message, string to) throws ioexception { 
  // session.getbasicremote().sendtext(message); 
  //session.getasyncremote().sendtext(message); 
  for (websocket item : clients.values()) { 
   if (item.username.equals(to) ) 
    item.session.getasyncremote().sendtext(message); 
  } 
 } 
 public void sendmessageall(string message) throws ioexception { 
  for (websocket item : clients.values()) { 
   item.session.getasyncremote().sendtext(message); 
  } 
 } 
 public static synchronized int getonlinecount() { 
  return onlinecount; 
 } 
 public static synchronized void addonlinecount() { 
  websocket.onlinecount++; 
 } 
 public static synchronized void subonlinecount() { 
  websocket.onlinecount--; 
 } 
 public static synchronized map<string, websocket> getclients() { 
  return clients; 
 } 
} 

客户端js

var websocket = null; 
var username = localstorage.getitem("name"); 
//判断当前浏览器是否支持websocket 
if ('websocket' in window) { 
 websocket = new websocket("ws://" + document.location.host + "/webchat/websocket/" + username + "/"+ _img); 
} else { 
 alert('当前浏览器 not support websocket') 
} 
//连接发生错误的回调方法 
websocket.onerror = function() { 
 setmessageinnerhtml("websocket连接发生错误"); 
}; 
//连接成功建立的回调方法 
websocket.onopen = function() { 
 setmessageinnerhtml("websocket连接成功"); 
} 
//接收到消息的回调方法 
websocket.onmessage = function(event) { 
 setmessageinnerhtml(event.data); 
} 
//连接关闭的回调方法 
websocket.onclose = function() { 
 setmessageinnerhtml("websocket连接关闭"); 
} 
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 
window.onbeforeunload = function() { 
 closewebsocket(); 
} 
//关闭websocket连接 
function closewebsocket() { 
 websocket.close(); 
} 

发送消息只需要使用websocket.send(“发送消息”),就可以触发服务端的onmessage()方法,当连接时,触发服务器端onopen()方法,此时也可以调用发送消息的方法去发送消息。关闭websocket时,触发服务器端onclose()方法,此时也可以发送消息,但是不能发送给自己,因为自己的已经关闭了连接,但是可以发送给其他人。

三、方法二:spring整合

websocketconfig.java

这个类是配置类,所以需要在spring mvc配置文件中加入对这个类的扫描,第一个addhandler是对正常连接的配置,第二个是如果浏览器不支持websocket,使用socketjs模拟websocket的连接。

package com.websocket; 
import org.springframework.context.annotation.bean; 
import org.springframework.context.annotation.configuration; 
import org.springframework.web.socket.config.annotation.enablewebsocket; 
import org.springframework.web.socket.config.annotation.websocketconfigurer; 
import org.springframework.web.socket.config.annotation.websockethandlerregistry; 
import org.springframework.web.socket.handler.textwebsockethandler; 
@configuration 
@enablewebsocket 
public class websocketconfig implements websocketconfigurer { 
 @override 
 public void registerwebsockethandlers(websockethandlerregistry registry) { 
  registry.addhandler(chatmessagehandler(),"/websocketserver").addinterceptors(new chathandshakeinterceptor()); 
  registry.addhandler(chatmessagehandler(), "/sockjs/websocketserver").addinterceptors(new chathandshakeinterceptor()).withsockjs(); 
 } 
 @bean 
 public textwebsockethandler chatmessagehandler(){ 
  return new chatmessagehandler(); 
 } 
} 

chathandshakeinterceptor.java

这个类的作用就是在连接成功前和成功后增加一些额外的功能,constants.java类是一个工具类,两个常量。

package com.websocket; 
import java.util.map; 
import org.apache.shiro.securityutils; 
import org.springframework.http.server.serverhttprequest; 
import org.springframework.http.server.serverhttpresponse; 
import org.springframework.web.socket.websockethandler; 
import org.springframework.web.socket.server.support.httpsessionhandshakeinterceptor; 
public class chathandshakeinterceptor extends httpsessionhandshakeinterceptor { 
 @override 
 public boolean beforehandshake(serverhttprequest request, serverhttpresponse response, websockethandler wshandler, 
   map<string, object> attributes) throws exception { 
  system.out.println("before handshake"); 
  /* 
   * if (request instanceof servletserverhttprequest) { 
   * servletserverhttprequest servletrequest = (servletserverhttprequest) 
   * request; httpsession session = 
   * servletrequest.getservletrequest().getsession(false); if (session != 
   * null) { //使用username区分websockethandler,以便定向发送消息 string username = 
   * (string) session.getattribute(constants.session_username); if 
   * (username==null) { username="default-system"; } 
   * attributes.put(constants.websocket_username,username); 
   * 
   * } } 
   */ 
  //使用username区分websockethandler,以便定向发送消息(使用shiro获取session,或是使用上面的方式) 
  string username = (string) securityutils.getsubject().getsession().getattribute(constants.session_username); 
  if (username == null) { 
   username = "default-system"; 
  } 
  attributes.put(constants.websocket_username, username); 
  return super.beforehandshake(request, response, wshandler, attributes); 
 } 
 @override 
 public void afterhandshake(serverhttprequest request, serverhttpresponse response, websockethandler wshandler, 
   exception ex) { 
  system.out.println("after handshake"); 
  super.afterhandshake(request, response, wshandler, ex); 
 } 
} 

chatmessagehandler.java

这个类是对消息的一些处理,比如是发给一个人,还是发给所有人,并且前端连接时触发的一些动作

package com.websocket; 
import java.io.ioexception; 
import java.util.arraylist; 
import org.apache.log4j.logger; 
import org.springframework.web.socket.closestatus; 
import org.springframework.web.socket.textmessage; 
import org.springframework.web.socket.websocketsession; 
import org.springframework.web.socket.handler.textwebsockethandler; 
public class chatmessagehandler extends textwebsockethandler { 
 private static final arraylist<websocketsession> users;// 这个会出现性能问题,最好用map来存储,key用userid 
 private static logger logger = logger.getlogger(chatmessagehandler.class); 
 static { 
  users = new arraylist<websocketsession>(); 
 } 
 /** 
  * 连接成功时候,会触发ui上onopen方法 
  */ 
 @override 
 public void afterconnectionestablished(websocketsession session) throws exception { 
  system.out.println("connect to the websocket success......"); 
  users.add(session); 
  // 这块会实现自己业务,比如,当用户登录后,会把离线消息推送给用户 
  // textmessage returnmessage = new textmessage("你将收到的离线"); 
  // session.sendmessage(returnmessage); 
 } 
 /** 
  * 在ui在用js调用websocket.send()时候,会调用该方法 
  */ 
 @override 
 protected void handletextmessage(websocketsession session, textmessage message) throws exception { 
  sendmessagetousers(message); 
  //super.handletextmessage(session, message); 
 } 
 /** 
  * 给某个用户发送消息 
  * 
  * @param username 
  * @param message 
  */ 
 public void sendmessagetouser(string username, textmessage message) { 
  for (websocketsession user : users) { 
   if (user.getattributes().get(constants.websocket_username).equals(username)) { 
    try { 
     if (user.isopen()) { 
      user.sendmessage(message); 
     } 
    } catch (ioexception e) { 
     e.printstacktrace(); 
    } 
    break; 
   } 
  } 
 } 
 /** 
  * 给所有在线用户发送消息 
  * 
  * @param message 
  */ 
 public void sendmessagetousers(textmessage message) { 
  for (websocketsession user : users) { 
   try { 
    if (user.isopen()) { 
     user.sendmessage(message); 
    } 
   } catch (ioexception e) { 
    e.printstacktrace(); 
   } 
  } 
 } 
 @override 
 public void handletransporterror(websocketsession session, throwable exception) throws exception { 
  if (session.isopen()) { 
   session.close(); 
  } 
  logger.debug("websocket connection closed......"); 
  users.remove(session); 
 } 
 @override 
 public void afterconnectionclosed(websocketsession session, closestatus closestatus) throws exception { 
  logger.debug("websocket connection closed......"); 
  users.remove(session); 
 } 
 @override 
 public boolean supportspartialmessages() { 
  return false; 
 } 
} 

spring-mvc.xml

正常的配置文件,同时需要增加对websocketconfig.java类的扫描,并且增加

xmlns:websocket="http://www.springframework.org/schema/websocket" 
    http://www.springframework.org/schema/websocket 
    <a target="_blank" href="http://www.springframework.org/schema/websocket/spring-websocket-4.1.xsd" rel="external nofollow" >http://www.springframework.org/schema/websocket/spring-websocket-4.1.xsd</a> 

客户端

<script type="text/javascript" 
  src="http://localhost:8080/bank/js/sockjs-0.3.min.js"></script> 
 <script> 
  var websocket; 
  if ('websocket' in window) { 
   websocket = new websocket("ws://" + document.location.host + "/bank/websocketserver"); 
  } else if ('mozwebsocket' in window) { 
   websocket = new mozwebsocket("ws://" + document.location.host + "/bank/websocketserver"); 
  } else { 
   websocket = new sockjs("http://" + document.location.host + "/bank/sockjs/websocketserver"); 
  } 
  websocket.onopen = function(evnt) {}; 
  websocket.onmessage = function(evnt) { 
   $("#test").html("(<font color='red'>" + evnt.data + "</font>)") 
  }; 
  websocket.onerror = function(evnt) {}; 
  websocket.onclose = function(evnt) {} 
  $('#btn').on('click', function() { 
   if (websocket.readystate == websocket.open) { 
    var msg = $('#id').val(); 
    //调用后台handletextmessage方法 
    websocket.send(msg); 
   } else { 
    alert("连接失败!"); 
   } 
  }); 
 </script> 

注意导入socketjs时要使用地址全称,并且连接使用的是http而不是websocket的ws

总结

以上所述是小编给大家介绍的java 实现websocket的两种方式实例详解,希望对大家有所帮助