zoukankan      html  css  js  c++  java
  • springBoot环境下创建webSocket服务端和客户端

    1.pom文件导入依赖

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>2.0.4.RELEASE</version>
    </dependency>

    2.创建webSocket相关配置

    复制代码
    package com.example.demo.mainDemo;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.WebSocketHandler;
    import org.springframework.web.socket.config.annotation.EnableWebSocket;
    import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
    import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
    
    @Configuration
    @EnableWebSocket
    public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(myHandler(), "myHandler").setAllowedOrigins("*");
    }
    public WebSocketHandler myHandler() {
    return new MyHandler();
    }
    
    }
    复制代码

    3.编写webSocket处理类,类似controller接口

    复制代码
    package com.example.demo.mainDemo;
    
    import com.alibaba.fastjson.JSONObject;
    import org.springframework.web.socket.TextMessage;
    import org.springframework.web.socket.WebSocketSession;
    import org.springframework.web.socket.handler.TextWebSocketHandler;
    
    import java.util.HashMap;
    import java.util.Map;
    
    /**
    * 相当于controller的处理器
    */
    public class MyHandler extends TextWebSocketHandler {
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    String payload = message.getPayload();
    // Map<String, String> map = JSONObject.parseObject(payload, HashMap.class);
    // System.out.println("=====接受到的数据"+map);
    session.sendMessage(new TextMessage("服务器返回收到的信息," + payload));
    }
    }
    复制代码



    4.编写客户端

    复制代码
    package com.example.demo.mainDemo.client;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import javax.websocket.*;
    
    @ClientEndpoint
    public class MyClient {
    private static Logger logger = LoggerFactory.getLogger(MyClient.class);
    private Session session;
    @OnOpen
    public void open(Session session){
    logger.info("Client WebSocket is opening...");
    this.session = session;
    }
    
    @OnMessage
    public void onMessage(String message){
    logger.info("Server send message: " + message);
    }
    
    @OnClose
    public void onClose(){
    logger.info("Websocket closed");
    }
    
    /**
    * 发送客户端消息到服务端
    * @param message 消息内容
    */
    public void send(String message){
    this.session.getAsyncRemote().sendText(message);
    }
    }
    复制代码

    5.创建main方法

    复制代码
    package com.example.demo.mainDemo.client;
    
    import javax.websocket.ContainerProvider;
    import javax.websocket.WebSocketContainer;
    import java.net.URI;
    
    public class ClientStart {
    public static void main(String[] args){
    try {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    MyClient client = new MyClient();
    container.connectToServer(client, new URI("ws://127.0.0.1:8080/myHandler"));
    // container.setDefaultMaxSessionIdleTimeout(5000L);
    int turn = 0;
    while(turn++ < 10){
    client.send("client send: 客户端消息 " + turn);
    Thread.sleep(1000);
    }
    }catch (Exception e){
    e.printStackTrace();
    }
    }
    }
    复制代码

    6.执行main方法

  • 相关阅读:
    IP地址加时间戳加3位随机数
    你会想造一艘船吗?
    提问的智慧
    建造者模式
    设计模式(一)
    jeesite中activiti中的流程表梳理
    如何读书、学习?
    zxing生成高容错率二维码,以及添加文字
    LVM磁盘划分
    阿里云盘扩容(SUSE Linux下)
  • 原文地址:https://www.cnblogs.com/xianz666/p/14439820.html
Copyright © 2011-2022 走看看