基于spring4 的websocket 简单示例

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



org.springframework
spring-websocket
4.2.0.RELEASE
 

org.springframework
spring-messaging
4.2.0.RELEASE

2.websocket服务端处理器
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);
	}
	

}

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();
    }

}

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

 
 

6.客户端页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>


	hello
	
    



 
   



你可能感兴趣的:(JAVA,WEB)