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

python_flask

flask踩过的坑
希望大家把遇到的问题都分享下,减少走弯路。
1.router不能统一管理,我采用Django模式把所有的路由都配置在urls文件中
2.router不能统一加载,没有找到像spring包扫描类似的工具类
3.TemplateNotFound静态资源找不到

4.debug模式 静态资源修改不生效,需要重启服务器
if name == ‘main‘:

#静态资源修改不需要重启
app.jinja_env.auto_reload = True
app.run(debug=True)
参考链接这里写链接内容
5.Template 引用静态资源 url_for

内心崩溃,同一篇文章第二次写,由于系统原因上一篇没发成功,也找不到了。
第二版就粗糙了些,请见谅,希望多提建议和分享遇到的坑。

相关代码下载地址:https://github.com/chatfree/flask_pit

|