更多课程 选择中心


Web培训

400-996-5531

Web培训

websocket+spring JAVA后端快速入门


websocket 是 Html5 新增加特性之一,目的是浏览器与服务端建立全双工的通信方式。

Handler处理类

一:实现 WebSocketHandler 接口

1234567

public interface WebSocketHandler { void afterConnectionEstablished(WebSocketSession session) throws Exception; 
void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception;
 void handleTransportError(WebSocketSession session, Throwable exception) throws Exception; 
void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception; boolean supportsPartialMessages();}
websocket+spring JAVA后端快速入门

二:扩展 AbstractWebSocketHandler

12345678910

@Servicepublic class ChatHandler extends AbstractWebSocketHandler { private static final Logger logger = LoggerFactory.getLogger(ChatHandler.class);
 private final static List<WebSocketSession> sessions = Collections.synchronizedList(new ArrayList<WebSocketSession>()); 
// handle text msg. @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) 
throws Exception { session.sendMessage(new TextMessage("hello world.")); }}

还可以重载其他三个方法:

123

handleBinaryMessage()handlePongMessage()handleTextMessage()
websocket+spring JAVA后端快速入门

三:扩展 TextWebSocketHandler

还可以重载afterConnectionEstablished() and afterConnectionClosed()方法:

123456789101112

// 当新连接建立的时候,被调用;public void afterConnectionEstablished(WebSocketSession session) throws Exception { #("Connection established");
 #("getId:" + session.getId()); # ("getLocalAddress:" + session.getLocalAddress().toString());
 # ("getUri:" + session.getUri().toString());}// 当连接关闭时被调用;@Overridepublic void afterConnectionClosed(WebSocketSession session,
 CloseStatus status) throws Exception { #("Connection closed. Status: " + status);}

四: 拦截器实现

12345678910111213141516

package com.websocket;@Service//如果采用WebSocketConfig类配置,需加上这一行;
采用XML配置则不用public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {@Overridepublic boolean beforeHandshake(ServerHttpRequest request,
 ServerHttpResponse response, WebSocketHandler wsHandler, 
Map<String, Object> attributes) throws Exception {if (request instanceof ServletServerHttpRequest) {attributes.put("username",userName);
}return true;}@Overridepublic void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {}}
websocket+spring JAVA后端快速入门

五: springMVC配置

方法一:编写 WebSocketConfig 配置类,实现 WebSocketConfigurer 接口。

123456789101112

@Configuration@EnableWebSocketpublic class WebSocketConfig implements WebSocketConfigurer{ @Autowired private ChatHandler chatHandler;
 @Autowired private WebSocketHandshakeInterceptor webSocketHandshakeInterceptor;
 @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry)
 { registry.addHandler(chatHandler,"/chat").addInterceptors(webSocketHandshakeInterceptor); }}

六:通过 XML 配置文件添加配置

12345678910111213141516

<bean id="chatHandler" class="com.websocket.ChatHandler"/><websocket:handlers><!-- 配置消息处理bean和路径的映射关系
 --><websocket:mapping path="/chat" handler="chatHandler"/><!-- 配置握手拦截器 
--><websocket:handshake-interceptors><bean class="com.websocket.WebSocketHandshakeInterceptor"/></websocket:handshake-interceptors><!-- 开启sockjs,
去掉则关闭sockjs --><websocket:sockjs/></websocket:handlers><!-- 配置websocket消息的最大缓冲区长度,
可以不配 --><bean class="org.springframework.web.socket.server.standard.
ServletServerContainerFactoryBean"><property name="maxTextMessageBufferSize" value="8192"/><property name="maxBinaryMessageBufferSize" value="8192"/></bean>
websocket+spring JAVA后端快速入门

七:controller实现

123456789101112131415161718192021222324

import org.springframework.messaging.handler.annotation.
MessageMapping;import org.springframework.stereotype.Controller;import org.springframework.
beans.factory.annotation.Autowired;import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.handler.annotation.DestinationVariable; import com.app.
deploying.model.Message;import com.spring.pojo.Greeting;import com.spring.pojo.HelloMessage;
@Controllerpublic class GreetingController { @Autowired private SimpMessagingTemplate simpMessagingTemplate;
 @MessageMapping("/room-message/{roomId}") public void roomMessage(Message message, @DestinationVariable String roomId)
{ String englishName = message.getTo(); String dest = "/message/" + roomId + "/" + englishName; LogConstant.runLog.
info(roomId+"号房间——"+"收到"+message.getFrom()+"发送至"+englishName+"的消息:"+"\""+message.getContent()+"\"");
 message.setDate(new Timestamp(System.currentTimeMillis())); this.simpMessagingTemplate.convertAndSend(dest, message); }}

前端代码暂无

预约申请免费试听课

填写下面表单即可预约申请免费试听! 怕学不会?助教全程陪读,随时解惑!担心就业?一地学习,可全国推荐就业!

上一篇:【Web配置】如何在web上导出excel?
下一篇:[Web安全]记一次钓鱼网站调查取证

怎样快速学会web渗透?

Web前端开发培训学习

微信小游戏怎么开发?

Web前端工程师需要掌握哪些知识?

Copyright © 2023 Tedu.cn All Rights Reserved 京ICP备08000853号-56 京公网安备 11010802029508号 达内时代科技集团有限公司 版权所有

选择城市和中心
黑龙江省

吉林省

河北省

贵州省

云南省

广西省

海南省