基于spring4 的websocket 简单示例

1.需要的类库基于maven配置

<!-- websocket -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>  
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>

2.websocket服务端处理器
<pre name="code" class="java">package com.sky.springmvc.websockets;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
/**
 * websocket 处理器
 * @author 孙效宁
 *
 */
public class WebsocketEndPoint extends TextWebSocketHandler{
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		super.handleTextMessage(session, message);
		TextMessage textMessage = new TextMessage(message.getPayload()+" received at server");
		
		System.err.println("message:"+message.getPayload());
		
		// 将客户端发送的信息原样输出
		session.sendMessage(textMessage);
	}
	
}


 
 

3.自定义握手接口(可选,如果有的话在配置的时候要加上,配置见4)

package com.sky.springmvc.websockets;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * websocket 处理器
 * @author 孙效宁
 *
 */
public class WebsocketEndPoint extends TextWebSocketHandler{

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		super.handleTextMessage(session, message);
		TextMessage textMessage = new TextMessage(message.getPayload()+" received at server");
		// 输出客户端发送的消息
		System.err.println("message:"+message.getPayload());
		
		// 将客户端发送的信息原样输出
		session.sendMessage(textMessage);
	}
	
<p>}</p>

4.服务端处理器和握手接口配置

package com.sky.springmvc.websockets;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * websocket 配置
 * @author 孙效宁
 *
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myHandler(), "/myHandler")
        	.addInterceptors(new HandshakeInterceptor())
        	.setAllowedOrigins("*").withSockJS();
    }

    @Bean
    public WebSocketHandler myHandler() {
        return new WebsocketEndPoint();
    }

<p>}</p>

5.springmvc 配置文件记得加上注解扫描

 <!-- 注解扫描器 -->
 <context:component-scan base-package="com.sky.springmvc"/>

6.客户端页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
	<title>hello</title>
	<script src="http://cdn.sockjs.org/sockjs-0.3.min.js">
    </script>
    <script>
	   var sock = new SockJS('http://localhost:8080/springmvc/myHandler');
	  	 sock.onopen = function() {
	       console.log('open');
	       // 给服务端发送简单文本消息
	       sock.send("test");
	   }; 
	   sock.onmessage = function(e) {
	       console.log('message', e.data);
	   };
	   sock.onclose = function() {
	       console.log('close');
	   };
	</script>
</head>
<body>
</body>
</html>

 
 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单WebSocket代码示例,使用Java的Spring Boot框架: 首先,添加依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 然后,创建一个WebSocket处理器类: ```java @Component public class WebSocketHandler extends TextWebSocketHandler { private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.add(session); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { // 处理收到的消息 } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session); } public void sendMessage(String message) throws IOException { for (WebSocketSession session : sessions) { session.sendMessage(new TextMessage(message)); } } } ``` 在该处理器类里,我们保存了所有连接的WebSocket会话,并实现了处理收到消息、建立连接和关闭连接的方法。还添加了一个`sendMessage`方法,该方法可以向所有连接的会话发送消息。 最后,在Spring Boot的配置文件中添加WebSocket相关配置: ```yaml spring: websocket: servlet: path: /websocket ``` 这样,客户端就可以通过`ws://localhost:8080/websocket`连接到WebSocket服务器了。在客户端发送消息时,服务器会调用`handleTextMessage`方法进行处理,并且可以调用`sendMessage`方法向客户端发送消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值