WebScoket

好久没更新博客了,太懒了,写了一段时间的WebScoket,简单写下我的理解

项目采用springBoot+WebScoket

通过springBoot快速生成一个gradle项目,打开 https://start.spring.io/

把下载的zip包解压并导入到idea中

#新建MyWebScoketConfig implements WebSocketConfigurer

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(getMyWebSocketHandler(),"/chat")
            .addInterceptors(new HttpSessionHandshakeInterceptor(){
        @Override
        public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                       WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpServletRequest httpServletRequest = servletRequest.getServletRequest();

            String mid = "1";//httpServletRequest.getHeader("mid");
            if(!StringUtils.isEmpty(mid)){
                attributes.put("mid",Long.valueOf(mid));
                return true;
            }
            return false;
        }

    }).setAllowedOrigins("*");
}
@Bean
public MyWebSocketHandler getMyWebSocketHandler(){
    return new MyWebSocketHandler();
}

#MyWebSocketHandler extends TextWebSocketHandler
static final Logger log = LoggerFactory.getLogger(MyWebSocketHandler.class);

static final Map<Long, WebSocketSession> sessions = new ConcurrentHashMap<>();

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    Long mid = getMid(session);
    log.info("connection "+mid);
    sessions.put(mid,session);
}

@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
    Long mid = getMid(session);
    log.info("close "+mid);
    sessions.remove(mid);
}

@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
    try {
        log.info("handleTransportError",exception);
        Long mid = getMid(session);
        session.close();
        sessions.remove(mid);
        log.info("websocket error: " + mid);
    } catch (Exception e) {
        log.error("handleTransportError error",e);
    }
}

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    log.info("接收到客户端消息:"+message.getPayload());
    session.sendMessage(new TextMessage("服务器回复消息:"+message.getPayload()));
}

public Long getMid(WebSocketSession session){
    return  (Long) session.getAttributes().getOrDefault("mid", null);
}

#配置文件采用yml方式
server:
port: 8888
session-timeout: 30
tomcat.max-threads: 0
tomcat.uri-encoding: UTF-8
spring:
application:
name: webscoket
logging:
level:
root: INFO
com:
jackfree:
webscoket: INFO

#build 配置
buildscript {
ext {
springBootVersion = ‘2.0.6.RELEASE’
}
repositories {
mavenCentral()
}
dependencies {
classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”)
}
}

apply plugin: ‘java’
apply plugin: ‘eclipse’
apply plugin: ‘org.springframework.boot’
apply plugin: ‘io.spring.dependency-management’

group = ‘com.jackfree’
version = ‘0.0.1-SNAPSHOT’
sourceCompatibility = 1.8

repositories {
mavenCentral()
}

dependencies {
implementation(‘org.springframework.boot:spring-boot-starter-websocket’)
testImplementation(‘org.springframework.boot:spring-boot-starter-test’)
}

#到这里简单的WebScoket就编写完成了

#js测试方法
ws = new WebSocket(“ws://localhost:8888/chat”);
// 建立 web socket 连接成功触发事件
ws.onopen = function () {
// 使用 send() 方法发送数据
ws.send(“client发送数据”);
};

// 接收服务端数据时触发事件
ws.onmessage = function (evt) { var received_msg = evt.data; alert(received_msg); };

// 断开 web socket 连接成功触发事件 ws.onclose = function () { alert(“连接已关闭…”); };

#源码地址 https://github.com/chatfree/webscoket

文章目录
  1. 1. 好久没更新博客了,太懒了,写了一段时间的WebScoket,简单写下我的理解
  • 项目采用springBoot+WebScoket
  • 通过springBoot快速生成一个gradle项目,打开 https://start.spring.io/
  • 把下载的zip包解压并导入到idea中
  • |