Websocket

来源:互联网 发布:软件环境是什么 编辑:程序博客网 时间:2024/06/11 20:22

今天尝试使用websocket

(1)添加依赖

<dependency>    <groupId>javax.websocket</groupId>    <artifactId>javax.websocket-api</artifactId>    <version>1.1</version></dependency>

(2)编写一个类,用serverendpoint注解

@ServerEndpoint(value = "/echo")public class EchoEndpointAnnotated {    @OnMessage    public String onMessage(String message, Session session) {        return message;    }}

(3)加另一部分依赖

To use Tyrus in standalone mode it is necessary to depend on correct Tyrus artifacts. The following artifacts need to be added to your pom to use Tyrus:

<dependency>    <groupId>org.glassfish.tyrus</groupId>    <artifactId>tyrus-server</artifactId>    <version>1.12</version></dependency><dependency>    <groupId>org.glassfish.tyrus</groupId>    <artifactId>tyrus-container-grizzly-server</artifactId>    <version>1.12</version></dependency>

(4)启动server,把写好的类加进去启动

Let's use the very same example like for Java API for WebSocket and deploy the EchoEndpointAnnotated on the standalone Tyrus server on the hostname "localhost", port 8025 and path "/websockets", so the endpoint will be available at address "ws://localhost:8025/websockets/echo".

public void runServer() {    Server server = new Server("localhost", 8025, "/websockets", null, EchoEndpoint.class);    try {        server.start();        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));        System.out.print("Please press a key to stop the server.");        reader.readLine();    } catch (Exception e) {        e.printStackTrace();    } finally {        server.stop();    }}
参考:https://tyrus-project.github.io/documentation/1.12/index/getting-started.html

原创粉丝点击