java项目应用webSocket的两种主要方式

点/击/蓝/字  关/注/我/们

一、背景

        笔者之前的项目中需要用webSocket协议进行长连接上游供应商,笔者为此做了一些小小的技术预研,特将此记录下来。

tips:因笔者主要是连接上游供应商的服务端,因此本文主要介绍webSocket客户端的知识,暂不编写服务端知识,请见谅。

        具体详细代码地址:

https://github.com/ikuncoder/webSocketConnector

二、javax

        在java的扩展包javax.websocket中已经定义了一套WebSocket的接口规范,应用起来比较简单快捷。

public class MainApplication {
    public static void main(String[] args) {
        connect();
    }
​
    private static void connect() {
        String url = "";//your websocket url,for example,wss://xxxxx.com/websocket/**
​
        // 实例化WebSocketService
        WebSocketService webSocketService = new WebSocketService();
​
        // 打开WebSocket连接
        try {
            webSocketService.openWebSocketConnection(url);
            //do something after connect
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

        首先创建一个WebSocketService对象,传入需要连接的url,需要是wss或者是ws开头的。

@ClientEndpoint
@Slf4j
public class WebSocketService {
​
    private Session userSession = null;
    private Long startTime = System.currentTimeMillis();
​
​
    public void openWebSocketConnection(String url) {
        try {
            URI uri = URI.create(url);
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            container.connectToServer(this, uri);
        } catch (Exception e) {
            throw new RuntimeException("Could not open WebSocket connection", e);
        }
    }
​
    @OnOpen
    public void onOpen(Session userSession) {
        System.out.println(Thread.currentThread().getName() + " Connection opened.");
        this.userSession = userSession;
    }
​
    @OnClose
    public void onClose(Session userSession, CloseReason reason) {
        System.out.println(Thread.currentThread().getName() + " 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值