websocket--demo(基于tio-websocket)

代码:

后端:

POM:

    <dependency>
            <groupId>org.t-io</groupId>
            <artifactId>tio-websocket-spring-boot-starter</artifactId>  
            <version>3.3.2.v20190601-RELEASE</version>
        </dependency>

配置类:


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"));
    }



}

前端:

<div>
    <button onclick="aa()">点击发送</button>
</div>
</body>
<script>
//该方法用于给后台发送数据
        function aa(){
            var ws = new WebSocket("ws://localhost:9876/");
            ws.onopen = function (event) {
                ws.send("Hello Tio WebSocket");
            }
        }
//以下代码用于接收客户端发送的数据
        var ws = new WebSocket("ws://localhost:9876/ws/msg");
       ws.onmessage = function (p1) {
        console.log(p1.data);
        var elementsByClassName = document.getElementsByClassName("message");
 elementsByClassName[0].innerText=p1.data//将其数据显示到页面
    }


</script>

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xixililicm

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值