socketio前后端交互

依赖:

    
        io.socket
        socket.io-client
        1.0.0
    
    
        com.corundumstudio.socketio
        netty-socketio
        1.7.16
    
    
        org.slf4j
        slf4j-nop
        1.7.2
    

后端:
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**

  • 类名称:SocketConfig

  • 类描述:socket.io 配置类

  • 创建时间:2019/4/320:22

  • 修改人:

  • 修改时间:

  • 修改备注:

  • @version 1.0.0

    */
    @Slf4j
    @Configuration
    public class SocketConfig {

    @Bean
    public SocketIOServer server() throws Exception {
    com.corundumstudio.socketio.Configuration configuration = new com.corundumstudio.socketio.Configuration();
    configuration.setHostname(“localhost”);
    configuration.setPort(9999);
    final SocketIOServer server = new SocketIOServer(configuration);
    return server;
    }

    @Bean
    public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
    return new SpringAnnotationScanner(socketServer);
    }
    }

import lombok.Data;

import java.util.Date;
import java.util.UUID;

/**

  • 类名称: Client

  • 类描述:socket.io在线对象实体类

  • 创建时间:2019/4/3 2:22

  • 修改人:

  • 修改时间:

  • 修改备注:

  • @version 1.0.0

    /
    @Data
    public class Client {
    /
    *

    • 客户端ID 同用户ID
      /
      private String clientId;
      /
      *
    • 客户端的SessionID
      /
      private UUID sessionId;
      /
      *
      客户端SessionID 大部分有意义的二进制数字
      /
      private long mostSignificantBits;
      /

      客户端SessionID 少部分有意义的二进制数字
      /
      private long leastSignificantBits;
      /
    • 最后连接时间
      */
      private Date lastConnectedTime;

    public String getClientId() {
    return clientId;
    }

    public void setClientId(String clientId) {
    this.clientId = clientId;
    }

    public UUID getSessionId() {
    return sessionId;
    }

    public void setSessionId(UUID sessionId) {
    this.sessionId = sessionId;
    }

    public long getMostSignificantBits() {
    return mostSignificantBits;
    }

    public void setMostSignificantBits(long mostSignificantBits) {
    this.mostSignificantBits = mostSignificantBits;
    }

    public long getLeastSignificantBits() {
    return leastSignificantBits;
    }

    public void setLeastSignificantBits(long leastSignificantBits) {
    this.leastSignificantBits = leastSignificantBits;
    }

    public Date getLastConnectedTime() {
    return lastConnectedTime;
    }

    public void setLastConnectedTime(Date lastConnectedTime) {
    this.lastConnectedTime = lastConnectedTime;
    }
    }

public interface Const{

// ======================CMC Start =======================
/**
 * COSMOSOURCE:(变量描述:cosmosource)
 */
String COSMOSOURCE = "cosmosource";
/**
 * CMC:(变量描述:cmc)
 */
String CMC = "cmc";
/**
 * UTF_8:(变量描述:UTF-8)
 */
String UTF_8 = "UTF-8";
/**
 * TOKEN:(变量描述:token)
 */
String TOKEN = "token";
/**
 * TOKEN:(变量描述:mene)
 */
String MENE = "mene";
/**
 * TOKEN:(变量描述:资源ID 1000)
 */
String NID = "1000";
/**
 * TOKEN:(变量描述:objType allC)
 */
String OBJTYPE = "allC";

/**
 * DOT:(变量描述:点)
 */
String DOT = ".";
/**
 * SLASH:(变量描述:斜杠)
 */
String SLASH = "/";
/**
 * BACK_SLASH:(变量描述:反斜杠)
 */
String BACK_SLASH = "\\";
/**
 * semicolon:(变量描述:分号)
 */
String SEMICOLON = ";";
/**
 * colon: (变量描述:冒号)
 */
String COLON = ":";
/**
 * COMMA:(变量描述:逗号)
 */
String COMMA = ",";
/**
 * SHIFT_15:(变量描述:<)
 */
String LESS_THAN = "<";
/**
 * SINGLE_QUOTE:(变量描述:单引号)
 */
String SINGLE_QUOTE = "'";
/**
 * PAH_E:(变量描述:%e)
 */
String PAH_E = "%e";
/**
 * SHIFT_10:(变量描述:`)
 */
String SHIFT_10 = "`";
/**
 * SHIFT_11:(变量描述:~)
 */
String SHIFT_11 = "~";
/**
 * SHIFT_1:(变量描述:!)
 */
String SHIFT_1 = "!";
/**
 * SHIFT_2:(变量描述:@)
 */
String SHIFT_2 = "@";
/**
 * SHIFT_3:(变量描述:#)
 */
String SHIFT_3 = "#";
/**
 * SHIFT_4:(变量描述:$)
 */
String SHIFT_4 = "$";
/**
 * SHIFT_5:(变量描述:%)
 */
String SHIFT_5 = "%";
/**
 * SHIFT_6:(变量描述:^)
 */
String SHIFT_6 = "^";
/**
 * SHIFT_7:(变量描述:&)
 */
String SHIFT_7 = "&";
/**
 * SHIFT_8:(变量描述:*)
 */
String SHIFT_8 = "*";
/**
 * SHIFT_9:(变量描述:()
 */
String SHIFT_9 = "(";
/**
 * SHIFT_0:(变量描述:))
 */
String SHIFT_0 = ")";
/**
 * SHIFT_12:(变量描述:-)
 */
String SHIFT_12 = "-";
/**
 * SHIFT_13:(变量描述:=)
 */
String SHIFT_13 = "=";
/**
 * SHIFT_14:(变量描述:_)
 */
String SHIFT_14 = "_";
/**
 * SHIFT_15:(变量描述:+)
 */
String SHIFT_15 = "+";
/**
 * NAME:(变量描述:NAME)
 */
String NAME = "name";
/**
 * FIELD:(变量描述:FIELD)
 */
String FIELD = "field";
/**
 * TABLE_NAME:(变量描述:TABLE_NAME)
 */
String TABLE_NAME = "TABLE_NAME";
/**
 * VIEW_NAME:(变量描述:VIEW_NAME)
 */
String VIEW_NAME = "VIEW_NAME";
/**
 * COLUMN_NAME:(变量描述:COLUMN_NAME)
 */
String COLUMN_NAME = "COLUMN_NAME";

/**
 * EMPTY:(变量描述:空)
 */
String EMPTY = "";

/**
 * COMMA:(变量描述:字符串0)
 */
String ZERO = "0";
/**
 * COMMA:(变量描述:字符串1)
 */
String ONE = "1";
/**
 * COMMA:(变量描述:字符串2)
 */
String TWO = "2";
/**
 * COMMA:(变量描述:字符串3)
 */
String THREE = "3";
/**
 * COMMA:(变量描述:字符串4)
 */
String FOUR = "4";
/**
 * COMMA:(变量描述:字符串5)
 */
String FIVE = "5";
/**
 * COMMA:(变量描述:字符串6)
 */
String SIX = "6";
/**
 * COMMA:(变量描述:字符串7)
 */
String SEVEN = "7";
/**
 * COMMA:(变量描述:字符串8)
 */
String EIGHT = "8";
/**
 * COMMA:(变量描述:字符串9)
 */
String NINE = "9";
/**
 * COMMA:(变量描述:字符串10)
 */
String TEN ="10";
/**
 * COMMA:(变量描述:字符串15)
 */
String FIFTEEN ="15";
/**
 * COMMA:(变量描述:字符串20)
 */
String TWENTY = "20";
/**
 * STATUS:(变量描述:status)
 */
String STATUS = "status";
/**
 * STATUS_UNDERWAY:(变量描述:正在进行)
 */
String STATUS_UNDERWAY = "正在进行";
/**
 * STATUS_OVER:(变量描述:结束)
 */
String STATUS_OVER = "结束";
/**
 * MSG:(变量描述:msg)
 */
String MSG = "msg";
/**
 * DATA:(变量描述:data)
 */
String DATA = "data";
/**
 * SUCCESS:(变量描述:success)
 */
String SUCCESS = "success";
/**
 * ERROR:(变量描述:error)
 */
String ERROR = "error";
/**
 * FAILED:(变量描述:failed)
 */
String FAILED = "failed";
/**
 * PROPERTY:(变量描述:property)
 */
String PROPERTY = "property";
/**
 * STYLE:(变量描述:style)
 */
String STYLE = "style";
/**
 * SYSTEM:(变量描述:system)
 */
String SYSTEM = "system";
/**
 * CUSTOM:(变量描述:custom)
 */
String CUSTOM = "custom";
/**
 * CSS:(变量描述:.css)
 */
String CSS = ".css";
/**
 * CSS:(变量描述:消息为空null_count)
 */
String NULL_COUNT = "null_count";
/**
 * CSS:(变量描述:.fail_count)
 */
String FAIL_COUNT = "fail_count";
/**
 * CSS:(变量描述:.success_count)
 */
String SUCCESS_COUNT = "success_count";

// ======================CMC End =======================

// ====================== Session Start =======================
/**
 * USER:(变量描述:User对象)
 */
String USER = "user";
/**
 * USERNAME:(变量描述:用户名)
 */
String USERNAME = "username";

// ====================== Session End =======================

// ====================== Other Start =======================

String DB_MYSQL = "mysql";
String DB_ORACLE = "oracle";
String DB_SQLSERVER = "sqlserver";

/**
 * TIME_10000:(变量描述:防刷时间)
 */
int TIME_10000 = 10000;

/**
 * TIME_10000:(变量描述:防刷时间)
 */
int TIME_5000 = 5000;
/**
 * HTML_INDEX:(变量描述:欢迎页)
 */
String HTML_INDEX = "index.html";
/**
 * HTML_403:(变量描述:无权限访问页)
 */
String HTML_403 = "/Unauthorized3.html";
/**
 * HTML_404:(变量描述:路径错误页面)
 */
String HTML_404 = "/NotFound.html";
/**
 * HTML_500:(变量描述:服务器异常页面)
 */
String HTML_500 = "/InternalServerError.html";
/**
 * HTML_503:(变量描述:频繁刷新页面)
 */
String HTML_503 = "/ServiceUnavailable.html";
/**
 * HTML_404:(变量描述:路径错误页面)
 */
String HTML_SESSIONTIMEOUT = "/SessionTimeout.html";
/**
 * LAST_VISIT_TIME:(变量描述:最后访问时间)
 */
String LAST_VISIT_TIME = "lastVisitTime";
/**
 * CALLBACK:(变量描述:回调)
 */
String CALLBACK = "callback";

/**
 * KEYPREFIX:(变量描述:Redis key前缀)
 */
//String KEYPREFIX = PropertyUtil.getStr("redis.keyPrefix");

/**
 * FWATERM:(变量描述:文字水印)
 */
String FWATERM = "宇动源";

/**
 * IWATERM:(变量描述:图片水印)
 */
String IWATERM = "";
String RIGHT_EDIT = "fwp_edit";
// ====================== Other End =======================

}

import com.corundumstudio.socketio.AckCallback;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.cosmosource.core.plugin.PageData;
import com.cosmosource.core.utils.GetSessionStatusUtil;
import com.cosmosource.model.socketio.Const;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicInteger;

import static javax.servlet.http.HttpServletResponse.SC_OK;

/**

  • @Description: socket.io 消息事件处理类 ******

  • @CreateDate: 2019/5/15 19:10

  • @UpdateDate: 2019/5/15 19:10

  • @UpdateRemark: 修改内容

  • @Version: 1.0
    */
    @Component
    @Slf4j
    public class MessageEventHandler implements Const {

    private static SocketIOServer server;

    @Autowired
    public MessageEventHandler(SocketIOServer server) {
    MessageEventHandler.server = server;
    }

    /**

    • connect事件处理,当客户端发起连接时将调用
    • @param client
      */
      @OnConnect
      public void onConnect(SocketIOClient client) throws Exception {
      System.out.println(“连接”);
      }

    /**

    • disconnect事件处理,当客户端断开连接时将调用
    • @param client
      */
      @OnDisconnect
      public void onDisconnect(SocketIOClient client) {
      System.out.println(“关闭”);

    }

    /**

    • 消息接收入口,当接收到消息后,查找发送目标客户端,并且向该客户端发送消息,且给自己发送消息

    • @param client

    • @param sessionId
      */
      @OnEvent(value = “chat_send_event”)
      public void onEvent(SocketIOClient client,String sessionId,AckRequest request) throws Exception {

      String sessionStatus = GetSessionStatusUtil.getSessionStatus(sessionId);

      // 给当前客户端推送消息内容
      client.sendEvent(“chat_get_event”, sessionStatus);

      //消息处理成功,给客户端回执
      if (request.isAckRequested()) {
      request.sendAckData(new JSONObject().element(STATUS, SC_OK).element(MSG, “发送成功”)
      .element(DATA, EMPTY));
      }
      }

}

import com.corundumstudio.socketio.SocketIOServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**

  • @Description: SocketIOServer 启动类 ******

  • @CreateDate: 2019/5/15 19:10

  • @UpdateDate: 2019/5/15 19:10

  • @UpdateRemark: 修改内容

  • @Version: 1.0
    */
    @Component
    public class ServerRunner implements CommandLineRunner {
    private final SocketIOServer server;

    @Autowired
    public ServerRunner(SocketIOServer server) {
    this.server = server;
    }

    @Override
    public void run(String… args) {
    server.start();
    }
    }

前端:
//socketIo
function socketIo(sessionId) {
var socket = io.connect(‘http://localhost:9999’);
/socket.on(‘connect’, function () {
});
/
sendMessage();
socket.on(‘chat_get_event’, function (data) {//聊天发送接收
console.log(“获取信息:” + data);
if (data == “idle”) {
page.announcement.push({
name: fileName,
id: sessionId,
});
//关闭socketio
sendDisconnect();

                }else if (data != "idle" && data != "starting" && data != "busy") {
                    alert("livy创建失败");
                    clearInterval(window.windowInterval);
                    window.clearInterval(window.windowInterval);
                    //关闭socketio
                    sendDisconnect();
                }else {
                    //继续查看Session状态
                    sendMessage();
                }
            });
            /*socket.on('disconnect', function () {
            });*/

            function sendMessage() {
                socket.emit('chat_send_event', sessionId)
            }
            function sendDisconnect() {
                socket.disconnect();
            }

           /* $(document).keydown(function (e) {
                if (e.keyCode == 13) {
                    $('#send').click();
                }
            });*/
        }

你可能感兴趣的:(socketio)