websocket--demo(基于tio-websocket)

代码:

后端:

POM:

    
            org.t-io
            tio-websocket-spring-boot-starter  
            3.3.2.v20190601-RELEASE
        

配置类:


public class MyWebSocketMsgHandler implements IWsMsgHandler {
    @Override
    public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        return httpResponse;
    }

    @Override
    public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        System.out.println("握手成功");
    }

    @Override
    public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        System.out.println("接收到bytes消息");
        return null;
    }

    @Override
    public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        return null;
    }

    @Override
    public Object onText(WsRequest wsRequest, String s, ChannelContext channelContext) throws Exception {
        System.out.println("接收到文本消息:" + s);
        return null;
    }

启动类:

@SpringBootApplication
@EnableTioWebSocketServer

public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

控制层:

@ServerEndpoint("/websocket")
@RequestMapping("/ws")
@RestController
public class Controller {
    @Autowired
    private TioWebSocketServerBootstrap bootstrap;

//该方法用于给前端发送数据
    @GetMapping("/msg")
    public void pushMessage(String msg) {
  
 
        Tio.sendToAll(bootstrap.getServerGroupContext(), WsResponse.fromText(msg, "utf-8"));
    }



}

前端:

 

你可能感兴趣的:(websocket,java)