WebSocket的简单使用

13 篇文章 0 订阅

介绍

WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocket API也被W3C定为标准。

WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输

介绍完直接上代码

 服务端

public class WebSocketServerDemo {

    static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
        WebSocketServer webSocketServer = new WebSocketServer() {
            @Override
            public void onOpen(WebSocket conn, ClientHandshake handshake) {
                System.out.println("welcome webSocket...");
            }

            @Override
            public void onClose(WebSocket conn, int code, String reason, boolean remote) {
                System.out.println("close webSocket...");
            }

            @Override
            public void onMessage(WebSocket conn, String message) {
                System.out.println("received client message: " + message);
                conn.send(simpleDateFormat.format(new Date()));
            }

            @Override
            public void onError(WebSocket conn, Exception ex) {
                ex.printStackTrace();
            }

            @Override
            public void onStart() {
                System.out.println("websocket start");
            }
        };
        webSocketServer.start();
    }
}

客户端

public class WebSocketClientDemo {

    public static void main(String[] args) throws URISyntaxException {
        WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://localhost:80")) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                String httpStatusMessage = handshakedata.getHttpStatusMessage();
                System.out.println("httpStatusMessage: " + httpStatusMessage);
            }

            @Override
            public void onMessage(String message) {
                System.out.println("received server message: " + message);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                System.out.println("close code: " + code);
                System.out.println("close reason: " + reason);
                System.out.println("close remote: " + remote);
            }

            @Override
            public void onError(Exception ex) {
                ex.printStackTrace();
            }
        };
        webSocketClient.connect();

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            int count = 0;
            @Override
            public void run() {
                if (webSocketClient.isOpen()) {
                    webSocketClient.send(String.valueOf(count++));
                }
            }
        }, 1000, 1000);
    }

okhttp版客户端

        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        Request request = new Request.Builder()
                .url("ws://localhost:80")
                .get()
                .build();
        WebSocket webSocket = okHttpClient.newWebSocket(request, new WebSocketListener() {

            @Override
            public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) {
                t.printStackTrace();
            }

            @Override
            public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
                System.out.println("received server message: " + text);
            }

            @Override
            public void onMessage(@NotNull WebSocket webSocket, @NotNull ByteString bytes) {
                String text = bytes.base64();
                System.out.println("received server message: " + text);

            }

            @Override
            public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
                System.out.println(response);
            }
        });

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            int count = 0;

            @Override
            public void run() {
                webSocket.send(String.valueOf(count++));
            }
        }, 1000, 1000);
    }

运行效果

 

 代码地址: https://github.com/LLAiden/webSocketDemo

代码中使用开源库: 'org.java-websocket:Java-WebSocket:1.5.2'

开源库地址: https://github.com/TooTallNate/Java-WebSockethttps://github.com/TooTallNate/Java-WebSocket

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值