WebSocket之ServerEndPoint

SpringBoot整合websocket实现及时通信聊天 线上演示地址:http://chat.breez.work 场景再现:构造函数如下所示: 例子如下: ??1.1.1 函数 1、 webSocket.send() 该函数用于向服务端发送一条消息,例子如下: 2、 webSocket.close() 该函数用于关闭客户端与服务端的连接,例子如下: ??1.1.2 事件 1、webSocket.onopen 该事件用于监听客户端与服务端的连接状态,如果客户端与服务端则该事件触发,例子如下: 2、webSocket.onclose 如果服务端与客户端连接断开,那 阅读详情

WebSocket是JavaEE7新支持的:

 

The javax.websocket.server package contains annotations, classes,and interfaces to create and configure server endpoints.

    Javax.websocket.server包含注解,类,接口用于创建和配置服务端点

The javax.websocket package contains annotations, classes,interfaces, and exceptions that are common to client and serverendpoints.

    Javax.websocket包则包含服务端点和客户断电公用的注解,类,接口,异常

 

To create a programmatic endpoint, you extend the Endpoint classand override its lifecycle methods.

创建一个编程式的端点,需要继承Endpoint类,重写它的方法。

To create an annotated endpoint, you decorate a Java class and someof its methods with the annotations provided by the packagesmentioned previously.

创建一个注解式的端点,将自己的写的类以及类中的一些方法用前面提到的包中的注解装饰(@EndPoint,@OnOpen等等)。

 

编程式注解示例:

 

@ServerEndpoint("/WebSocketServer")

public class ServerEndPoint808

{

 

@OnOpen

public void start(Sessionsession)

{

System.out.println("连接成功! " +session.getId());

}

 

@OnMessage

public void reMessage(Session session, Stringstr)

{

try

{

session.getBasicRemote().sendText(str+ " who areyou");

}

catch (IOExceptione)

{

e.printStackTrace();

}

}

 

@OnError

public void error(Session session, Throwablet)

{

t.printStackTrace();

 

}

 

@OnClose

public void close()

{

 

}

 

After you have created an endpoint,you deploy it to an specific URI in the application so that remoteclients can connect to it.

当创建好一个(服务)端点之后,将它以一个指定的URI发布到应用当中,这样远程客户端就能连接上它了。

 

WebSocket endpoints are representedby URIs that have the following form:

Websocket(服务)端点以URI表述,有如下的访问方式:

ws://host:port/path?query

wss://host:port/path?query

 

注解详解:

@ServerEndPoint:

    RequiredElements :

        Value: URI映射

    OptionalElemens:

        subprotocols:

        decoders:解码器

        encoders:编码器

        configurator:

Annotation

Event

Example

OnOpen

Connection opened

@OnOpen

Public void open(Sessionsession,

EndpointConfig conf) { }

OnMessage

Message received

@OnMessage

public void message(Sessionsession,

String msg) { }

OnError

Connection error

@OnError

public void error(Sessionsession,

Throwable error) { }

OnClose

Connection closed

@OnClose

public void close(Sessionsession,

CloseReason reason) { }

 

建立连接相关:

The Session parameter represents aconversation between this endpoint and the remoteendpoint.

Session代表着服务端点与远程客户端点的一次会话。

 

Because the container creates aninstance of the endpoint class for every connection, you can defineand use instance variables to store client stateinformation.

容器会为每一个连接创建一个EndPoint的实例,需要利用实例变量来保存一些状态信息。

 

the Session.getUserProperties methodprovides a modifiable map to store user

Session.getUserProperties提供了一个可编辑的map来保存properties,

properties. For example, thefollowing endpoint replies to incoming text messages

例如,下面的端点在收到文本消息时,将前一次收到的消息回复给其他的端点

with the contents of the previousmessage from each client:

 

@ServerEndpoint("/delayedecho")

public class DelayedEchoEndpoint

{

@OnOpen

public void open(Sessionsession)

{

session.getUserProperties().put("previousMsg", "");

}

 

@OnMessage

public void message(Session session, Stringmsg)

{

 

String prev= (String) session.getUserProperties().get("previousMsg");

 

session.getUserProperties().put("previousMsg",msg);

try {

session.getBasicRemote().sendText(prev);

 

    } catch (IOException e){ ... }

}

}

To store information common to allconnected clients, you can use class (static) variables; however,you are responsible for ensuring thread-safe access tothem

 

发送、接收消息:

WebSocket endpoints can send andreceive text and binary messages. In addition, they can also sendping frames and receive pong frames.

Websocketendpoint能够发送和接收文本、二进制消息,另外,也可以发送ping帧和接收pong 帧

发送消息:

  1. Obtain the Session object from theconnection.

    从连接中获得Session对象

    The Session object is available as aparameter in the annotated lifecycle methods of the endpoint, likethose in Table 18–1.

        Session对象是endPoint中那些被注解标注的方法中可得到的参数

When your message is a response to amessage from the peer,

当你的message作为另外的消息的响应

you have the Session objectavailable inside the method that received the message (the methodannotated with @OnMessage).

在@OnMessage标注的方法中,有session对象接收message

If you have to send messages thatare not responses, store the Session object as an instance variableof the endpoint class in the method annotated with@OnOpen

如果你必须主动发送message,需要在标注了@OnOpen的方法中将session对象作为实例变量保存

so that you can access it from othermethods.

这样,你可以再其他方法中得到该session对象

 

  1. Use the Session object to obtain aRemote Endpoint object.

    通过Session对象获得Remoteendpoint对象

    The Session.getBasicRemotemethod andthe Session.getAsyncRemotemethod

    return RemoteEndpoint.BasicandRemoteEndpoint.Asyncobjects respectively.

    The RemoteEndpoint.Basicinterfaceprovides blocking methods to send

    messages; theRemoteEndpoint.Asyncinterface provides nonblockingmethods.

  2. Use the RemoteEndpoint object to sendmessages to the peer.

    利用RemoteEndpoint对象来发送message

    The following list shows some of themethods you can use to send messages to the

    peer.

    ■ voidRemoteEndpoint.Basic.sendText(String text)

    Send a text message to the peer.This method blocks until the whole message

    has been transmitted.

    ■ voidRemoteEndpoint.Basic.sendBinary(ByteBuffer data)

    Send a binary message to the peer.This method blocks until the whole

    message has beentransmitted.

    ■ voidRemoteEndpoint.sendPing(ByteBuffer appData)

    Send a ping frame to thepeer.

    ■ voidRemoteEndpoint.sendPong(ByteBuffer appData)

    Send a pong frame to thepeer.

代码示例:

@ServerEndpoint("/echoall")

public class EchoAllEndpoint

{

@OnMessage

public void onMessage(Session session, Stringmsg)

{

try {

for (Session sess :session.getOpenSessions())

{

if (sess.isOpen())

sess.getBasicRemote().sendText(msg);

}

} catch (IOExceptione) { ... }

}

}

接收消息:

TheOnMessage annotation designates methods that handle incomingmessages.

OnMessage注解指定方法来处理接收的messages

You canhave at most three methods annotated with @OnMessage in anendpoint,

在一个端点类中,至多可以为三个方法标注@OnMessage注解

one foreach message type: text, binary, and pong.

消息类型分别为:text、binary、pong。

 

Encoders and Decoders(编码器和解码器):

The Java API for WebSocket providessupport for converting between WebSocket messages and custom Javatypes using encoders and decoders.

WebSocket Api 提供了encoders 和decoders用于 Websocket Messages 与传统java 类型之间的转换

An encoder takes a Java object andproduces a representation that can be transmitted as a WebSocketmessage;

编码器输入java对象,生成一种表现形式,能够被转换成Websocketmessage

for example, encoders typicallyproduce JSON, XML, or binary representations.

例如:编码器通常生成json、XML、二进制三种表现形式

A decoder performs the reversefunction; it reads a WebSocket message and creates a Javaobject.

解码器执行相反的方法,它读入Websocket消息,然后输出java对象

编码器编码:

  1. Implement one of the followinginterfaces:

    Encoder.Textfor textmessages

    Encoder.Binaryfor binarymessages

    These interfaces specify the encodemethod. Implement an encoder class for each custom Java type thatyou want to send as a WebSocket message.

    这些接口指定编码方法,为你想作为WebsocketMessage传递的java 类型实现编码类

  2. Add the names of your encoderimplementations to the encoders optional parameter of theServerEndpoint annotation.

     

    将实现的编码器类的names添加到@ServerEndPoint注解中

     

  3. Use the sendObject(Object data) methodof the RemoteEndpoint.Basic or RemoteEndpoint.Async interfaces tosend your objects as messages. The container

looks for an encoder thatmatches your type and uses it to convert the object to a WebSocketmessage.

利用RemoteEndpoint.Basic或者RemoteEndpoint.Async的sendObject(Objectdata)方法将对象作为消息发送,容器寻找一个符合此对象的编码器,

利用此编码器将此对象转换成Websocketmessage

代码示例:

public class MessageATextEncoder implements Encoder.Text

{

@Override

public void init(EndpointConfig ec) {}

@Override

public void destroy() {}

@Override

public String encode(MessageAmsgA) throws EncodeException

{

// Access msgA's properties and convert to JSONtext...

return msgAJsonString;

}

}

Then, add theencodersparameter to the ServerEndpointannotation asfollows:

@ServerEndpoint(

value= "/myendpoint",

encoders ={ MessageATextEncoder.class, MessageBTextEncoder.class }

)

解码器解码:

  1. Implement one of the followinginterfaces:

     

    Decoder.Textfor textmessages

Decoder.Binaryfor binarymessages

These interfaces specify thewillDecode and decode methods.

  1. Add the names of your decoderimplementations to the decoders optional parameter of theServerEndpoint annotation.

     

  2. Use the OnMessage annotation in theendpoint to designate a method that takes your custom Java type asa parameter.

     

    When the endpoint receives amessage that can be decoded by one of the decoders youspecified,

the container calls themethod annotated with @OnMessage that takes your custom Java typeas a parameter if this method exists.

public class MessageTextDecoder implements Decoder.Text

{

@Override

public void init(EndpointConfigec)

{

}

 

@Override

public void destroy()

{

}

 

@Override

public Message decode(Stringstring) throws DecodeException

{

// Read message...

if (  )

return new MessageA(...);

else if (  )

return new MessageB(...);

}

 

@Override

public boolean willDecode(Stringstring)

{

// Determine if the message can be converted into eithera

// MessageA object or a MessageB object...

return canDecode;

}

}

 

Then, add thedecoderparameter to the ServerEndpointannotation asfollows:

 

@ServerEndpoint(

value= "/myendpoint",

encoders ={ MessageATextEncoder.class, MessageBTextEncoder.class },

decoders ={ MessageTextDecoder.class }

)

 

处理错误:

Todesignate a method that handles errors in an annotated WebSocketendpoint, decorate it with @OnError:

 

为一个注解式的端点指定一个处理error的方法,为此方法加上@OnError注解:

 

@ServerEndpoint("/testendpoint")

public class TestEndpoint{

...

@OnError

public void error(Session session, Throwablet)

{

t.printStackTrace();

...

}

}

 

This methodis invoked when there are connection problems, runtime errors frommessage handlers, or conversion errors when decodingmessages.

 

当出现连接错误,运行时错误或者解码时转换错误,该方法才会被调用

 

指定端点配置类:

The JavaAPI for WebSocket enables you to configure how the containercreates server endpoint instances.

 

Websocket的api允许配置容器合适创建serverendpoint 实例

 

You canprovide custom endpoint configuration logic to:

 

Access thedetails of the initial HTTP request for a WebSocketconnection

Performcustom checks on the OriginHTTP header

Modify theWebSocket handshake response

Choose aWebSocket subprotocol from those requested by the client

Control theinstantiation and initialization of endpoint instances

 

To providecustom endpoint configuration logic, you extend theServerEndpointConfig.Configurator class and override some of itsmethods.

继承ServerEndpointConfig.Configurator 类并重写一些方法,来完成customendpoint configuration 的逻辑代码

In theendpoint class, you specify the configurator class using theconfigurator parameter of the ServerEndpoint annotation.

 

代码示例:

public class CustomConfigurator extends ServerEndpointConfig.Configurator

{

@Override

public void modifyHandshake(ServerEndpointConfigconf,

HandshakeRequest req, HandshakeResponseresp)

{

conf.getUserProperties().put("handshakereq",req);

}

}

 

Thefollowing endpoint class configuresendpoint instances with thecustom configurator, which enables them to access the handshakerequest object:

 

@ServerEndpoint(

value ="/myendpoint",

configurator= CustomConfigurator.class

)

 

public class MyEndpoint

{

@OnOpen

public void open(Session s, EndpointConfigconf)

{

HandshakeRequest req= (HandshakeRequest)conf.getUserProperties()

.get("handshakereq");

Map> headers =req.getHeaders();

...

}

}

WebSocket详解(Java后端,基于Springboot) WebSocket是一种在单个TCP连接上进行全双工通信的协议。这种协议在2011年被IETF定为标准RFC 6455,并由RFC7936补充规范,同时WebSocket API也被W3C定为标准。它使得客户端和服务器之间的数据交换变得更加简单,特别是允许服务端主动向客户端推送数据。实时性更高:WebSocket技术可以实现实时通信,传输数据的延迟更低,因此可以更快地将数据传输到客户端。减少网络带宽的使用:通过建立一个持久化的连接,WebSocket减少了HTTP协议中每次请求和响应所需要的网络带宽。 阅读详情

相关推荐

SpringBoot整合WebSocket服务 springboot整合websocket springboot使用websocket springboot使用websocket

仅使用 SpringBoot封装好的服务,并不是使用第三方Netty或者: 底层使用实现: 底层使用Netty实现(没有使用过,不知道具体)官方文档1官方文档2。

web17886480312的博客 6765

@ServerEndpoint 注解的作用

@ServerEndpoint 注解的作用

weixin_43652507的博客 2万+

Java API 实现实时通信的WebSocket应用

它允许服务器端和客户端之间建立持久的连接,并通过该连接进行实时数据传输。本文将介绍如何使用Java WebSocket API进行实时通信,并提供相应的源代码示例。最后,我们可以运行WebSocket服务器和客户端,实现实时通信。当用户输入消息后,客户端会将该消息发送给服务器,并打印服务器返回的消息。通过使用WebSocket API,我们可以轻松地在Java应用程序中实现实时通信功能,例如在线聊天、实时数据更新等。首先,我们需要创建一个WebSocket服务器端来处理客户端的连接请求和消息传递。

TechWhizZ的博客 253

websocket (@ServerEndpoint)基本使用指南

websocket (@ServerEndpoint)基本使用指南

墨鸦的博客 2万+

极化码理论及算法研究6-SCL、CA-SCL及matlab仿真

极化码译码算法5——SCL/CA-SCL译码算法系列目录1、引言2、串行抵消列表(SCL)译码算法2.1、路径度量PM 系列目录 (如要找其他内容,欢迎访问我的主页寻找) #前言 #极化码概述 #极化码定义 #极化码编码 #极化码译码 #5G标准中极化码的编译码概述 #5G标准中极化码的编码 #5G标准中极化码的译码 #总结 1、引言 在上一节中,介绍了经典的SC译码算法的理论原理以及其matlab仿真代码,SC译码算法具有较低的译码复杂度,但是由于每个译码的比特信息都依赖于前面所有的比特信息的译码结果,得

1万+

智能解决装箱问题:使用优化算法实现高效包装

装箱问题(Bin Packing Problem)是组合优化领域中的一个经典问题,主要涉及如何将一系列对象高效地装入有限数量的容器(或“箱”)中,同时满足特定的约束条件。这个问题的目标是最小化所需使用的箱子数量或者最大化箱子的装载效率,以减少空间或资源的浪费。

MindOpt_003的博客 5545

ServerEndpoint 无法注入bean的问题

ServerEndpoint 无法注入bean的问题 在springmvc项目中配置websocket的环境,给客户端发送消息模块,变量无法注入,值为空   @Autowired   private Mydata mydata; /** ...

awyo96572的博客 3131

用MATLAB从零实现六足机器人步态仿真:交替三角与波动步态保姆级教程

本文详细介绍了如何使用MATLAB从零实现六足机器人的两种经典步态仿真:交替三角支撑步态和波动步态。通过参数定义、相位设置、运动轨迹生成和三维可视化等步骤,帮助读者掌握六足机器人步态规划的核心技术。教程包含完整代码和详细解析,适合机器人爱好者和相关专业学生学习实践。

weixin_26765363的博客 226

在 Spring Boot 中整合、使用 WebSocket

WebSocket 是一种基于 TCP 协议的全双工通信协议,它允许客户端和服务器之间建立持久的、双向的通信连接。相比传统的 HTTP 请求 - 响应模式,WebSocket 提供了实时、低延迟的数据传输能力。通过 WebSocket,客户端和服务器可以在任意时间点互相发送消息,实现实时更新和即时通信的功能。WebSocket 协议经过了多个浏览器和服务器的支持,成为了现代 Web 应用中常用的通信协议之一。

Go_ahead_forever的博客 4046

别再瞎改注册表了!实测Win10/Win11远程桌面60帧的正确姿势(附ToDesk对比)

本文深入解析Windows远程桌面60帧优化的科学方法,揭示常见误区并提供实测有效的解决方案。从版本差异到硬件加速,再到第三方工具对比(如ToDesk),帮助用户避开无效的注册表修改,实现流畅的远程桌面体验。

weixin_33738555的博客 341

ICC2: pin shape不在track上引起的drc如何解决?

我正在「拾陆楼」和朋友们讨论有趣的话题,你⼀起来吧?

m0_61544122的博客 433

Springboot 使用 webSocket

正值金三银四招聘旺季,很多小伙伴都询问我有没有前端方面的面试题,特地整理出来赠送给大家!资料领取方式:点击这里前往获取适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!**[外链图片转存中…(img-9dF7PO8Y-1712477114928)]由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:前端)

2301_82244182的博客 876

汽车电子RTOS--AUTOSAR OS

AUTOSAR OS(AUTomotive Open System ARchitecture Operating System)是AUTOSAR(汽车开放系统架构)标准中的一个重要组件,它是一个专门为汽车电子控制单元(ECU)设计的实时操作系统(RTOS)。AUTOSAR OS旨在提供一个标准化的软件平台,以促进不同供应商和汽车制造商之间的组件复用和协同开发,提高软件质量和降低成本。

MHD0815的博客 1797

serverendpoint注解_传统@ServerEndpoint方式开发WebSocket应用和SpringBoot构建WebSocket应用程序...

小Hub领读:通过websocket的两种使用方式,让你更加深入理解用法。很多人不懂websocket怎么辨别是谁发送过来的,文中说到实现WebSocketConfigurer接口,定义拦截器可以绑定用户信息,还有其他很多,细细品,对比看比较好!文末有源码地址~对了,看完记得点个[ 在看 ]支持一下哈。作者:编码妙妙屋https://www.skypyb.com/2019/02/jish...

weixin_39637723的博客 1万+

企业财务共享服务中心业务蓝图规划方案【附全文阅读】

《企业财务共享服务中心业务蓝图规划方案》为集团企业提供财务共享中心建设全流程指导,涵盖战略定位、组织架构、业务流程、信息系统、运营管理和变革实施六大维度。方案明确共享中心"交易处理+战略支撑"双重职能,设计专业分组架构,筛选标准化高、价值明确的流程(如核算、资金结算等)纳入共享范围,构建业财一体化平台,并配套绩效与风险管控体系。结合项目型企业管理特点,分阶段推进实施,助力企业实现财务集中化与标准化转型。

cdfunlove的博客 994

基于深度学习的异常检测实战:从自编码器到GAN

本文通过一个完整的实战案例,展示了如何使用自编码器和GAN进行异常检测。我们详细介绍了数据准备、模型定义、训练和评估的步骤,并提供了可运行的代码。希望本文能为读者在实际项目中应用异常检测技术提供实用的指导和启发。

Programming Talk 242

springboot整合websocket,超简单入门

WebSocket 是一种基于 TCP 协议的全双工通信协议,它允许客户端和服务器之间建立持久的、双向的通信连接。相比传统的 HTTP 请求 - 响应模式,WebSocket 提供了实时、低延迟的数据传输能力。通过 WebSocket,客户端和服务器可以在任意时间点互相发送消息,实现实时更新和即时通信的功能。WebSocket 协议经过了多个浏览器和服务器的支持,成为了现代 Web 应用中常用的通信协议之一。它广泛应用于聊天应用、实时数据更新、多人游戏等场景,为 Web 应用提供了更好的用户体验

我认不到你的博客 1073

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

WebSocket connection to,Error during WebSocket handshake: Unexpected response code: 404

原博客地址:http://www.oschina.net/question/1756518_238747 ServerEndpoint这些注解是JavaEE7的内容,记得Tomcat得要8.0才能支持。Tomcat7的话,WebSocket是靠Servlet继承WebSocketServlet 来实现的

taoshengyijiuzt的专栏 7316

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

webSocket连接测试

根据ServerEndpoint里面 path 的配置 来调整。先找到你的 webSocket的连接工具。

liyingqi123的博客 389

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

springboot整合websocket实现群聊 + 私信,可提供源码

websocket怎么说呢,就是服务器可以主动向客户端发起对话! 这样就很好理解了吧! 咱们先上效果图: 相对来说更好看那么一点但是,实现代码都是一样的。我们先来准备工作导入依赖 <!--websocket依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-st

nanxiang11的博客 5190

springBoot和Websocket(tomcat/netty)

基于web服务器的websocket pom <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> 使用 注入ServerEndpointExporter @Bean public ServerE

echola的专栏 1570

websocket @ServerEndpoint注解说明

首先我们查看一下ServerEndpoint类源码: @Retention(value = RetentionPolicy.RUNTIME) @Target(value = {ElementType.TYPE}) public @interface ServerEndpoint { public String value(); public String[] subpro...

那些年的代码 4763

springboot版本的websocket单体和多实例(分布式部署)

# websocket-demo 架构图 项目介绍 基于websocket-springboot-starter的一个demo,1.0演示了基本的WebSocketManager的使用,包括单机和集群的, 1.1版本在1.0版本基础上实现了多ServerEndPoint和对WerbSocketManager管理,他们的关系一般是一对一的。 软件架构 基于websocket和SpringBoot 码云地址 ...

风吹麦浪的专栏 2596

springmvc转springboot之使用websocket

前几篇已经将项目转换成springboot了。发现还有websocket忘记配置了,现在简单配置一下保证可以使用先。 1、首先引入websocket的依赖 <!-- websocket --> <dependency> <groupId>org.springframework.boot</grou...

asd372506589的博客 517

Websocket实现方式二——注解方式

Websocket Spring-Websocket

sinat_36230171的博客 669
上一篇: secureCRT 使用 rz 命令上传大文件失败出现乱码
下一篇: springcloud项目中eureka-server、eureka-client、config-server、zuul互相如何通信请求
qq_34412985
博客等级 码龄11年 143粉丝 983原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值