java WebSocket 实现

包含 Java 实现的 websocket 的完整例子

一、 maven 主要依赖

    <dependencies>
        <!-- https://mvnrepository.com/artifact/javax.websocket/javax.websocket-api -->
        <dependency>
            <groupId>javax.websocket</groupId>
            <artifactId>javax.websocket-api</artifactId>
            <version>1.1</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

    </dependencies>

二、注解介绍

@ServerEndpoint
声明websocket地址,类似于Spring MVC中的@controller注解,websocket使用@ServerEndpoint来进行声明接口:@ServerEndpoint(value="/websocket/{paraName}") ; 其中 “ { } ”用来表示带参数的连接,如果需要获取{}中的参数在参数列表中增加:@PathParam(“paraName”) String userId 。

@OnOpen
有连接时的触发函数。 我们可以在用户连接时记录用户的连接带的参数,只需在参数列表中增加参数:@PathParam(“paraName”) String paraName。

@OnClose
连接关闭时的调用方法。

@OnMessage
收到消息时调用的函数,其中Session是每个websocket特有的数据成员

@OnError
发生意外错误时调用的函数

示例代码:https://github.com/ChaseDreamBoy/websocket-demo/blob/master/src/main/java/com/xh/socket/MyServerEndpoint.java

三、成员数据介绍

Session
每个Session代表了两个web socket断点的会话;当websocket握手成功后,websocket就会提供一个打开的Session,可以通过这个Session来对另一个端点发送数据;如果Session关闭后发送数据将会报错。

Session.getBasicRemote().sendText(“message”)
向该Session连接的用户发送字符串数据。

四、websocket-demo

https://github.com/ChaseDreamBoy/websocket-demo

五、jetty

项目使用 jetty 容器,启动方式:
start project

六、效果

message

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值