关于java:websocket入门开发

9次阅读

共计 2995 个字符,预计需要花费 8 分钟才能阅读完成。

1、引入 pom
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-websocket</artifactId>
</dependency>
2、配置 webSocket 类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
    /**
     * ServerEndpointExporter 作用
     * 这个 Bean 会主动注册应用 @ServerEndpoint 注解申明的 websocket endpoint
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();
    }
}
3、编写 webSocket 服务
@ServerEndpoint(value = "/api/applet/websocket")
@Component
public class AppletWebSocket {
    /**
     * 动态变量,用来记录以后在线连接数
     */
    private volatile static int onlineCount = 0;

    /**
     * concurrent 包的线程平安 Set,用来寄存每个客户端对应的 MyWebSocket 对象。*/
    private volatile static CopyOnWriteArraySet<AppletWebSocket> webSocketSet = new CopyOnWriteArraySet<AppletWebSocket>();

    /**
     * 与某个客户端的连贯会话,须要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 用户标识
     */
    private Long userId;

    /**
     * 连贯建设胜利调用的办法
     * 每次新建链接时,查问该用户的状态
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException, EncodeException {
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();}

    /**
     * 连贯敞开调用的办法
     */
    @OnClose
    public void onClose() {webSocketSet.remove(this);
        subOnlineCount();}

    /**
     * 收到客户端音讯后调用的办法
     *
     * @param message 客户端发送过去的音讯
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {sendMessage(message));
        } catch (IOException e) {System.out.println(e);
        }
    }

    /**
     * 产生谬误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {System.out.println("产生谬误");
        error.printStackTrace();}


    public void sendMessage(String message) throws IOException {this.session.getBasicRemote().sendText(message);
    }


    /**
     * 群发自定义音讯
     */
    public static void sendInfo(String message) throws IOException {for (AppletWebSocket item : webSocketSet) {
            try {item.sendMessage(message);
            } catch (IOException e) {continue;}
        }
    }

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

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

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

    public CopyOnWriteArraySet<AppletWebSocket> getWebSocketSet() {return webSocketSet;}

    public Long getUserId() {return userId;}

    public Session getSession() {return session;}
}
4、测试接口是否失常

关上在线测试网址:http://coolaf.com/tool/chattest

输出本人的服务地址,记得 url 是以 ws:// 结尾的

测试失常即可在本人的程序中援用,具体已业务规定为准。

5、集体倡议

AppletWebSocket 类中须要退出用户标识,不便零碎被动推送信息时,辨别用户。

可启动多个 socket 服务。

6、经验的坑

1)本地能够失常连贯,公布到服务器显示 404

请依照一下状况查看:

a. nginx 配置查看

location /websocket/applet {
  #websocket 配置
  proxy_connect_timeout 4s;
  proxy_read_timeout 7200s; #超过 7200 秒(两小时)内没通信则断连
  proxy_send_timeout 12s;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  proxy_pass http://localhost:8587/websocket/applet;
}

b. 请 ping 下你的域名,查看是否指向你服务器的 ip 地址

win + R 关上 dos 窗口
ping 你的域名

我就是这种状况,始终报 404,然而我其余接口没问题,查看之后发现是我的 www.51bishe.site 应用了 cdn 减速,指向的是减速的地址,导致统一报 404.

如果应用域名不行,能够应用 ip 地址的形式进行测试,放大排查范畴。

c. 如果你的服务器用的是 https 的加密协议,记得你的 soket 申请地址是以 wss:// 结尾。

本文由博客一文多发平台 OpenWrite 公布!

正文完
 0