spring-boot + websocket

引入 依赖

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>

创建websocket endpoint

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author: fumin
 * @Description:
 * @Date: Create in 2019/7/17 9:24
 */
@ServerEndpoint("/api/webSocket")
@RestController
public class WebSocket {
    // 用来记录当前连接数的变量
    private static volatile int onlineCount = 0;

    // concurrent包的线程安全Set,用来存放每个客户端对应的Session对象
	private static CopyOnWriteArraySet<Session> socketSession = new CopyOnWriteArraySet<Session>();

    // 与某个客户端的连接会话,需要通过它来与客户端进行数据收发
    private Session session;

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocket.class);


    @OnClose
    public void onClose(Session session) {
        socketSession .remove(session);
        LOGGER.info("Close a websocket. ");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
	    socketSession.add(session);
        LOGGER.info("Receive a message from client: " + message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        LOGGER.error("Error while websocket. ", error);
    }

    public void sendMessage(String message) throws Exception {
        if (this.session.isOpen()) {
            this.session.getBasicRemote().sendText("Send a message from server. ");
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }
}

配置websocket


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @Author: fumin
 * @Description: websocket 配置
 * @Date: Create in 2019/7/15 15:19
 */
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

调用端, 使用 java websocket

引入依赖

<!-- https://mvnrepository.com/artifact/org.java-websocket/Java-WebSocket -->
        <dependency>
            <groupId>org.java-websocket</groupId>
            <artifactId>Java-WebSocket</artifactId>
            <version>1.3.8</version>
        </dependency>
package com.hckj.iot;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;

/**
 * @Author: fumin
 * @Description:
 * @Date: Create in 2019/7/17 8:36
 */
public class TestWebSocketClient extends WebSocketClient {
    private final Logger LOGGER = LoggerFactory.getLogger(TestWebSocketClient.class);

    public TestWebSocketClient(URI serverUri) {
        super(serverUri);
    }

    public TestWebSocketClient(URI serverUri, Draft protocolDraft) {
        super(serverUri, protocolDraft);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        LOGGER.info("Open a WebSocket connection on client. ");
    }

    @Override
    public void onClose(int arg0, String arg1, boolean arg2) {
        LOGGER.info("Close a WebSocket connection on client. ");
    }

    @Override
    public void onMessage(String msg) {
        LOGGER.info("WebSocketClient receives a message: " + msg);
    }

    @Override
    public void onError(Exception exception) {
        LOGGER.error("WebSocketClient exception. ", exception);
    }
}

public static void main(String[] args) throws  Exception{

//        String serverUrl = "ws://10.1.3.4:8111/testWebSocket/121/1";
        String serverUrl = "ws://10.1.3.4:8030/api/webSocket";
        URI recognizeUri = new URI(serverUrl);
        TestWebSocketClient  client = new TestWebSocketClient(recognizeUri, new Draft_6455());

        client.connect();

//        Thread.sleep(2000);
        // 连接完马上调用 send的话会报错
        client.send("This is a message from client. ");

    }

在这里插入图片描述
注意: 如果不设置睡眠 会报连接成功, 但是发送失败
注意: 如果有配置了 shiro的, 会被shiro拦截, 需要配置地址过滤

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值