springBoot websocket使用

4 篇文章 0 订阅
2 篇文章 0 订阅

java websocket API (JSR-356) 是开发websocket 的 java api 集合

 

术语 : 端点(Endpoint) , 连接(connection) ,对点(peer),

会话(session), 客户端端点,服务端端点

 

 

端点生命周期(endpoint lifecyle)

打开连接 Endpoint#

@ OnOpen onOpen(Session var1, EndpointConfig var2)

 

关闭连接:

@onClose onClose(Session session, CloseReason closeReason)

错误: @OnError onError(Session session, Throwable throwable)

 

 

会话(sessions)

API : javax.websocket.session

 

接收消息:javax.websocket.messageHandler

 

发送消息 : javax.websocket.RemoteEndpoint.Basic

 

 

服务端配置类:javax.websocket.ServerEndpointConfig

客户端配置类:javax.websocket.ClientEndpointConfig

 

版本spring boot 1.5.14

 

服务类

package cn.shendu.server;

 

import org.springframework.stereotype.Component;

 

import javax.websocket.*;

import javax.websocket.server.PathParam;

import javax.websocket.server.ServerEndpoint;

import java.io.IOException;

import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

 

@ServerEndpoint(value = "/chat-room/{username}")

public class WebSocketServer {

// 统计在线人数

private static Map<String,Session> livingSessions =

new ConcurrentHashMap<String,Session>();

 

@OnOpen

public void openSession(@PathParam("username") String username,Session session){

String sessionId = session.getId();

livingSessions.put(sessionId,session);

 

sendTextAll("欢迎用户["+username+"] 来到聊天室! ");

 

}

@OnMessage

public void onMessage(@PathParam("username") String username,Session session,String message){

sendTextAll("用户["+username+"]: "+message);

}

 

@OnClose

public void onClose(@PathParam("username") String username,Session session){

String sessionId = session.getId();

//当前的session 移除

livingSessions.remove(sessionId);

//并且通知其他人当前用户已经离开聊天室

sendTextAll("用户["+username+"]已经离开聊天室了!");

}

 

 

private void sendText(Session session,String message){

RemoteEndpoint.Basic basic = session.getBasicRemote();

try {

basic.sendText(message);

} catch (IOException e) {

e.printStackTrace();

}

}

 

private void sendTextAll(String message){

livingSessions.forEach((sessionId,session)->{

sendText(session,message);

});

}

 

}

 

 

html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

 

<title>聊天室</title>

<script src="https://code.jquery.com/jquery-3.2.1.min.js" ></script>

 

</head>

 

<body>

聊天消息内容:

<br/>

<textarea id="text_chat_content" readonly="readonly" cols="100" rows="9">

 

</textarea>

 

<br/>

 

用户:<input id="in_user_name" value=""/>

<button id="btn_join">加入聊天室</button>

<button id="btn_exit">离开聊天室</button>

 

<br/>

 

输入框:<input id="in_msg" value=""/><button id="btn_send">发送消息</button>

 

<script type="text/javascript">

$(document).ready(function(){

var urlPrefix ='ws://127.0.0.1:8080/chat-room/';

var ws = null;

$('#btn_join').click(function(){

var username = $('#in_user_name').val();

var url = urlPrefix+username;

ws = new WebSocket(url);

ws.onmessage = function(event){

//服务端发送的消息

$('#text_chat_content').append(event.data+'\n');

}

ws.onclose = function(event){

$('#text_chat_content').append('用户['+username+'] 已经离开聊天室!');

}

});

//客户端发送消息到服务器

$('#btn_send').click(function(){

var msg = $('#in_msg').val();

if(ws){

ws.send(msg);

}

});

//离开聊天室

$('#btn_exit').click(function(){

if(ws){

ws.close();

}

});

})

</script>

 

</body>

 

</html>

 

 

启动类

package cn.shendu.websocket;

 

import cn.shendu.server.WebSocketServer;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.Bean;

import org.springframework.web.socket.config.annotation.EnableWebSocket;

import org.springframework.web.socket.server.standard.ServerEndpointExporter;

 

@EnableWebSocket

@SpringBootApplication

public class WebsocketApplication {

 

public static void main(String[] args) {

SpringApplication.run(WebsocketApplication.class, args);

}

 

@Bean

public ServerEndpointExporter serverEndpointExporter(){

return new ServerEndpointExporter();

}

 

@Bean

public WebSocketServer webSocketServer(){

return new WebSocketServer();

}

}

 

maven 依赖

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

 

<groupId>cn.shendu</groupId>

<artifactId>websocket</artifactId>

<version>0.0.1-SNAPSHOT</version>

<packaging>jar</packaging>

 

<name>websocket</name>

<description>Demo project for Spring Boot</description>

 

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>1.5.4.RELEASE</version>

<relativePath/> <!-- lookup parent from repository -->

</parent>

 

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<java.version>1.8</java.version>

</properties>

 

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-websocket</artifactId>

</dependency>

 

<dependency>

<groupId>io.netty</groupId>

<artifactId>netty-all</artifactId>

<version>5.0.0.Alpha2</version>

</dependency>

 

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

 

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

 

 

</project>

 

 

参考

小马哥spring boot 教程

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Spring Boot开发WebSocket应用程序可以使用@ClientEndpoint注解。@ClientEndpoint注解是从javax.websocket.ClientEndpoint注解派生的,它指示Spring Boot应用程序中的类是WebSocket客户端端点。通过使用该注解,可以轻松地将WebSocket客户端端点与WebSocket服务器进行连接。 以下是使用@ClientEndpoint注解的示例: ```java @ClientEndpoint public class WebSocketClientEndpoint { private Session session; @OnOpen public void onOpen(Session session) { this.session = session; } @OnMessage public void onMessage(String message) { System.out.println("Received message: " + message); } @OnClose public void onClose() { System.out.println("WebSocket closed"); } @OnError public void onError(Throwable t) { System.out.println("WebSocket error occurred: " + t.getMessage()); } public void sendMessage(String message) { this.session.getAsyncRemote().sendText(message); } } ``` 在上面的示例中,@ClientEndpoint注解用于标记WebSocket客户端端点。此类使用@OnOpen、@OnMessage、@OnClose和@OnError注解来实现WebSocket的不同生命周期事件。sendMessage()方法用于向WebSocket服务器发送消息。 要使用@ClientEndpoint注解,必须在应用程序中启用WebSocket。可以使用Spring Boot的@EnableWebSocket注解启用WebSocket。例如: ```java @SpringBootApplication @EnableWebSocket public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` 通过这样做,您可以使用@ClientEndpoint注解创建WebSocket客户端端点,并使用WebSocket服务器进行通信。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值