websocket学习

写在前面

新公司用到了websocket技术,所以这里学习下。

1:Java原生

1.1:maven

xml 复制代码
<dependency>
    <groupId>org.java-websocket</groupId>
    <artifactId>Java-WebSocket</artifactId>
    <version>1.5.3</version>
</dependency>

1.2:server

java 复制代码
public class SocketServer extends WebSocketServer {

    public SocketServer(int port) throws UnknownHostException {
        super(new InetSocketAddress(port));
    }

    public SocketServer(InetSocketAddress address) {
        super(address);
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        conn.send("Welcome to the server!"); // This method sends a message to the new client
        broadcast("new connection: " + handshake
                .getResourceDescriptor()); // This method sends a message to all clients connected
        System.out.println(
                conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!");
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        broadcast(conn + " has left the room!");
        System.out.println(conn + " has left the room!");
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        broadcast(message + "by server");
        System.out.println(conn + ": " + message);
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        ex.printStackTrace();
        if (conn != null) {
            // some errors like port binding failed may not be assignable to a specific
            // websocket
        }
    }

    @Override
    public void onStart() {
        System.out.println("Server started!");
        setConnectionLostTimeout(0);
        setConnectionLostTimeout(100);
    }
}

1.3:main

java 复制代码
public class MyMain {
    public static void main(String[] args) throws InterruptedException, IOException {
        int port = 8887; // 843 flash policy port
        SocketServer s = new SocketServer(port);
        s.start();
        System.out.println("ChatServer started on port: " + s.getPort());

        BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String in = sysin.readLine();
            s.broadcast(in);
            if (in.equals("exit")) {
                s.stop(1000);
                break;
            }
        }
    }

}

启动:

SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
ChatServer started on port: 8887
Server started!

1.4:测试

我们使用如下的工具 来测试:

在地址框录入地址ws://localhost:8887,测试如下:

可以再调试工具查看交互的过程:

2:java原生+springboot

2.1:pom

xml 复制代码
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.7.7</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
</dependencies>

2.2:程序

  • 定义连接端点endpoint
java 复制代码
@ServerEndpoint("/myWs")
@Component
public class WsServerEndpoint {

    /**
     * 连接成功
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("连接成功");
    }

    /**
     * 连接关闭
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        System.out.println("连接关闭");
    }

    /**
     * 接收到消息
     *
     * @param text
     */
    @OnMessage
    public String onMsg(String text) throws IOException {
        return "servet 发送:" + text;
    }
}
  • 暴漏服务
java 复制代码
@Configuration
@EnableWebSocket
public class WebsocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpoint() {
        return new ServerEndpointExporter();
    } 

}
  • main
java 复制代码
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

启动:

...
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.7)

2023-11-17 11:26:14.827  INFO 24100 --- [           main] a.b.App                                  : Starting App using Java 1.8.0_202 on DESKTOP-C3DTETT with PID 24100 (E:\workspace-idea\dongshidaddy-labs-new\javabase\websocket\java_origin_and_boot\target\classes started by dell9020 in E:\workspace-idea\dongshidaddy-labs-new)
2023-11-17 11:26:14.891  INFO 24100 --- [           main] a.b.App                                  : No active profile set, falling back to 1 default profile: "default"
...
2023-11-17 11:26:50.299  INFO 24100 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
  • 测试

写在后面

参考文章列表

java实现websocket的五种方式

相关推荐
Erik_LinX22 分钟前
day1-->day7| 机器学习(吴恩达)学习笔记
笔记·学习·机器学习
索然无味io38 分钟前
组件框架漏洞
前端·笔记·学习·安全·web安全·网络安全·前端框架
珊瑚里的鱼1 小时前
【单链表算法实战】解锁数据结构核心谜题——环形链表
数据结构·学习·程序人生·算法·leetcode·链表·visual studio
林涧泣1 小时前
图的矩阵表示
学习·线性代数·矩阵
chimchim661 小时前
【starrocks学习】之catalog
学习
Future_yzx1 小时前
基于SpringBoot+WebSocket的前后端连接,并接入文心一言大模型API
spring boot·websocket·文心一言
梦云澜2 小时前
论文阅读(二):理解概率图模型的两个要点:关于推理和学习的知识
论文阅读·深度学习·学习
Ronin-Lotus2 小时前
上位机知识篇---CMake
c语言·c++·笔记·学习·跨平台·编译·cmake
lxl13073 小时前
学习数据结构(2)空间复杂度+顺序表
数据结构·学习
Zfox_4 小时前
HTTP cookie 与 session
linux·服务器·网络·c++·网络协议·http