最近在做的两个系统中都用到了webSocket,一个是实时转译系统,该系统就是通过收集端收音,然后实时将录音转换成文字显示到页面上,第二个是智能客服系统。由于之前用webSocket比较少,一直以为在创建连接的时候,不能传递参数,直到有一天看源码的时候,发现了新大陆,下面分享一下
1、在被websocket映射的Java类中的注解如下:
@ServerEndpoint("/websocket/{relationId}/{userCode}")
2、在该Java类中的方法中:
@OnOpen public void onOpen(@PathParam("relationId") String relationId, @PathParam("userCode") int userCode, Session session)
这样就可以获取第一步中的两个参数的值(relationId和userCode)
3、在客户端调用的时候 url:ws:localhost:8090/websocket/2/1
这样我们就完美解决了,之前我们的解决方式都是,在链接成功以后,双方定义一个报文格式,然后传递初始化参数,相对于这种方式还是非常麻烦的。
4、源码如下:
package javax.websocket; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This method level annotation can be used to decorate a Java method that wishes to be called when a new * web socket session is open. * * <p>The method may only take the following parameters:- * <ul> * <li>optional {@link Session} parameter</li> * <li>optional {@link EndpointConfig} parameter</li> * <li>Zero to n String parameters annotated with the {@link javax.websocket.server.PathParam} annotation.</li> * </ul> * * <p>The parameters may appear in any order. * * @author dannycoward */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OnOpen { } Zero to n String parameters annotated with the {@link javax.websocket.server.PathParam} annotation.</li> * </ul> * * <p>The parameters may appear in any order. * * @author dannycoward */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OnOpen { }