首页
学习
活动
专区
圈层
工具
发布

socket系列(二)——Javaee实现实时通信

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/luo4105/article/details/72692184

实现

java自带javaee-api7.0实现

环境要求

Tomcat7.0以上支持(最好tomcat8.0以上)

Ie7,8,9不支持,可以有sockeJS代替

Jar包:javaee-api-7.0.jar

项目结构

Java代码

代码语言:javascript
复制
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
 
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
 
@ServerEndpoint(value = "/websocket")
public classPushSocket {
 
    // 连接人数
    private static int count;
 
    private staticCopyOnWriteArraySet<PushSocket> set = new CopyOnWriteArraySet<>();
 
    // 服务端与客户端的通话
    private Session session;
 
    @OnOpen
    public void onOpen(Session session) {
       this.session = session;
       set.add(this);
       addOnlineCount();
       System.out.println("服务器在线人数:" + getOnlineCount());
    }
 
    @OnClose
    public void onClose(Session session) {
       set.remove(this);
       subOnlineCount();
       System.out.println("服务器在线人数:" + getOnlineCount());
    }
 
    @OnMessage
    public void onMessage(String message, Session session) {
       System.out.println("来自客户端的消息:" + message);
       // 群发消息
       for (PushSocket socket : set) {
           try {
              System.out.println(socket.hashCode());
              socket.sendMsg(message);
           }catch(IOException e) {
              e.printStackTrace();
              continue;
           }
       }
    }
 
    @OnError
    public void onError(Session session, Throwable error) {
       System.out.println("发生错误");
       error.printStackTrace();
    }
 
    /**
     * 某个连接发送消息
     * @param msg
     */
    public void sendMsg(String msg) throws IOException {
       this.session.getBasicRemote().sendText(msg);
    }
 
    public static int getOnlineCount() {
       return count;
    }
 
    public static void addOnlineCount() {
       count++;
    }
 
    public static void subOnlineCount() {
       count--;
    }
}

Jsp代码

代码语言:javascript
复制
<%@ page language="java"contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
       <meta charset="UTF-8">
       <title>socket</title>
       <script type="text/javascript" src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
    <body>
       welcome<br />
       <input id="text" type="text"/>
       <button οnclick="sendMsg()">sendMsg</button>
       <hr/>
       <button οnclick="closeWebSocket()">close WebSocketconnection</button>
       <hr/>
       <div id="message"></div>
    </body>
   
    <script type="text/javascript">
       var websocket = null;
       //判断浏览器是否支持websocket
       if('WebSocket' in window) {
           websocket= newWebSocket("ws://localhost:8080/study_push/websocket");
       }else{
           $("#message").html("该浏览器不支持实时通信功能");
       }
      
       websocket.onopen= function() {
           console.log("websocket连接成功");
       }
      
       websocket.onclose= function() {
           console.log("websocket连接关闭");
       }
      
       websocket.onmessage= function(event) {
           console.log("接收消息");
           console.log(event);
           printMsg(event.data);
       }
      
       //打印消息
       function printMsg(msg) {
           $("#message").append(msg+ "<br/>");
       }
      
       function sendMsg() {
           var msg = $("#text").val();
           websocket.send(msg);
       }
      
       function closeWebSocket(){
           websocket.close();
       }
    </script>
</html>

Web.xml配置

代码语言:javascript
复制
<?xml version="1.0"encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>study_push</display-name>
    <welcome-file-list>
       <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

运行

打开” http://localhost:8080/study_push/IMpage.jsp”,实现情况

总结

Javaee-api对于websocket的处理十分轻便,好用便捷。

Java代码:

"@ServerEndpoint(value ="/websocket")":tomcat就会默认把该标签的类当作一个websocket,value就是连接地址。

"@OnOpen":当有新的连接时执行方法,这里执行的是给session赋值,添加该连接对象,增加连接数量,打印连接信息。

"@OnClose":当有连接关闭时执行方法,这里执行的是移除连接对象和打印信息操作。

"@OnMessage":当有新消息传后台时执行方法,这里执行的是给所有连接对象发送该请求。

"@OnError":当有连接错误时执行方法。

每当有新的客户端连接时,都会创建一个新的PushSocket对象,所以这里用CopyOnWriteArraySet<PushSocket>set来存放所有的连接对象。

Js代码:

"websocket = new WebSocket()":连接服务器websocket,参数就是服务器websocket地址

"websocket.onopen":连接后执行。

"websocket.onclose":关闭执行。

"websocket.onmessage":服务器发送消息。

ie7、8、9不支持websocket,可以使用socketJS替代

下一篇
举报
领券