前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >socket系列(二)——Javaee实现实时通信

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

作者头像
逝兮诚
发布2019-10-30 13:20:39
6580
发布2019-10-30 13:20:39
举报
文章被收录于专栏:代码人生

版权声明:本文为博主原创文章,遵循 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替代

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/05/24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 实现
  • 运行
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档