代码如下
@ServerEndpoint(value = “/websocket/{rName}/{uName}”)可以作为服务端 @ClientEndpoint 作为客户端使用, 主要有三个类, URI: 指定服务端的webSocket请求地址 ContainerProvider: 提供一个socket容器 WebSocketContainer: 提供连接方法,并获取session.
@Component
@ClientEndpoint
public class MyWebSocketClient {
private final static Logger logger = LoggerFactory.getLogger(MyWebSocketClient.class);
private String uri;
// @Value用在方法上可以注入静态属性
@Value("${dppz.websocketUrl}")
public void setUri(String uri) {
this.uri = uri;
}
@OnOpen
public void onOpen(Session session) {}
@OnMessage
public void onMessage(String message) {
System.out.println("Client onMessage: " + message);
}
@OnClose
public void onClose() {
}
public void sendMsg(String param) {
WebSocketContainer container = null;
try {
container = ContainerProvider.getWebSocketContainer();
URI r = URI.create(uri);
Session session = container.connectToServer(MyWebSocketClient.class, r);
session.getBasicRemote().sendText(param);
session.close();
} catch (Exception e) {
logger.error(ExceptionUtil.getDeatilExceptionInfo(e));
}
}
}
|