博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springMvc + websocket 实现点对点 聊天通信功能
阅读量:6821 次
发布时间:2019-06-26

本文共 9241 字,大约阅读时间需要 30 分钟。

一,web - demo链接如下(tomcat-websocket):

 

二, springMvc + websocket 实现点对点通信

1,pom.xml 增加spring-websocket.jar

1     
3
4
org.springframework
5
spring-websocket
6
${spring.version}
7

 

2,登陆  - login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%    String path = request.getContextPath();    String basePath = request.getScheme() + "://"            + request.getServerName() + ":" + request.getServerPort()            + path + "/";%>socket - login
username:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.socket.TextMessage;import com.aisino.core.user.entity.User;@RequestMapping("websocket")@Controllerpublic class UserController {    @Autowired    private MsgScoketHandle msgScoketHandle;    @RequestMapping("login")    public String login(String username, HttpServletRequest request){        User user = new User();        user.setReal_name(username);        request.getSession().setAttribute("user",user);        request.getSession().setAttribute("username", username);        return "soket/soket";    }            @ResponseBody    @RequestMapping("sendMsg")    public String sendMag(String content,String toUserName){        User user = new User();        user.setReal_name(toUserName);        TextMessage textMessage = new TextMessage(content);        msgScoketHandle.sendMessageToUser(user,textMessage);        return "200";    }}

 

3,点对点通信  socket - chat.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%    String path = request.getContextPath();    String basePath = request.getScheme() + "://"            + request.getServerName() + ":" + request.getServerPort()            + path + "/";%>socket - chat     当前登录用户:${username}
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;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;@Configuration@EnableWebMvc@EnableWebSocketpublic class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer{    private static final Logger logger = LoggerFactory.getLogger(WebSocketConfig.class);    @Override    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {        System.out.println("==========================注册socket");        //注册websocket server实现类,"/webSocketServer"访问websocket的地址        registry.addHandler(msgSocketHandle(),                "/webSocketServer").                addInterceptors(new WebSocketHandshakeInterceptor());        //使用socketjs的注册方法        registry.addHandler(msgSocketHandle(),                "/sockjs/webSocketServer").                addInterceptors(new WebSocketHandshakeInterceptor())                .withSockJS();    }     /**     *     * @return 消息发送的Bean     */    @Bean(name = "msgSocketHandle")    public WebSocketHandler msgSocketHandle(){        return new MsgScoketHandle();    }}
import java.util.Map;import javax.servlet.http.HttpSession;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.server.ServerHttpRequest;import org.springframework.http.server.ServerHttpResponse;import org.springframework.http.server.ServletServerHttpRequest;import org.springframework.web.socket.WebSocketHandler;import org.springframework.web.socket.server.HandshakeInterceptor;import com.aisino.core.user.entity.User;public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {   private static final Logger logger = LoggerFactory.getLogger(WebSocketHandshakeInterceptor.class);    /**     * 握手前     * @param request     * @param response     * @param webSocketHandler     * @param attributes     * @return     * @throws Exception     */    @Override    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, Map
attributes) throws Exception { logger.info("握手操作"); if (request instanceof ServletServerHttpRequest){ ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) request; HttpSession session = servletServerHttpRequest.getServletRequest().getSession(false); if(session != null){ //从session中获取当前用户 User user = (User) session.getAttribute("user"); attributes.put("user",user); } } return true; } /** * 握手后 * @param serverHttpRequest * @param serverHttpResponse * @param webSocketHandler * @param e */ @Override public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) { }}
import java.io.IOException;import java.util.ArrayList;import org.springframework.stereotype.Component;import org.springframework.web.socket.CloseStatus;import org.springframework.web.socket.TextMessage;import org.springframework.web.socket.WebSocketHandler;import org.springframework.web.socket.WebSocketMessage;import org.springframework.web.socket.WebSocketSession;import com.aisino.core.user.entity.User;import com.google.common.collect.Lists;@Componentpublic class MsgScoketHandle implements WebSocketHandler {    /**已经连接的用户*/    private static final ArrayList
users; static { //保存当前连接用户 users = Lists.newArrayList(); } /** * 建立链接 * @param webSocketSession * @throws Exception */ @Override public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception { //将用户信息添加到list中 users.add(webSocketSession); System.out.println("=====================建立连接成功=========================="); User user = (User) webSocketSession.getAttributes().get("user"); if(user != null){ System.out.println("当前连接用户======"+user.getReal_name()); } System.out.println("webSocket连接数量====="+users.size()); } /** * 接收消息 * @param webSocketSession * @param webSocketMessage * @throws Exception */ @Override public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage
webSocketMessage) throws Exception { User user = (User) webSocketSession.getAttributes().get("user"); System.out.println("收到用户:"+user.getReal_name()+"的消息"); System.out.println(webSocketMessage.getPayload().toString()); System.out.println("==========================================="); } /** * 异常处理 * @param webSocketSession * @param throwable * @throws Exception */ @Override public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable){ if (webSocketSession.isOpen()){ //关闭session try { webSocketSession.close(); } catch (IOException e) { } } //移除用户 users.remove(webSocketSession); } /** * 断开链接 * @param webSocketSession * @param closeStatus * @throws Exception */ @Override public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception { users.remove(webSocketSession); User user = (User) webSocketSession.getAttributes().get("user"); System.out.println(user.getReal_name()+"断开连接"); } @Override public boolean supportsPartialMessages() { return false; } /** * 发送消息给指定的用户 * @param user * @param messageInfo */ public void sendMessageToUser(User user, TextMessage messageInfo){ for (WebSocketSession session : users) { User sessionUser = (User) session.getAttributes().get("user"); //根据用户名去判断用户接收消息的用户 if(user.getReal_name().equals(sessionUser.getReal_name())){ try { if (session.isOpen()){ session.sendMessage(messageInfo); System.out.println("发送消息给:"+user.getReal_name()+"内容:"+messageInfo); } break; } catch (IOException e) { e.printStackTrace(); } } } }}

 

4,注意点,使用Tomcat8以上,tomcat7会报错(貌似与tomat-websocket 冲突)

 demo地址:https://files.cnblogs.com/files/xiexy/springMvc-websocket.zip

 

转载于:https://www.cnblogs.com/xiexy/p/4070562.html

你可能感兴趣的文章
maven下运行jetty报错
查看>>
android 配置framework 使应用首选安装在SD卡
查看>>
h5 点击表单 顶部fixed 菜单栏 上移
查看>>
windows 2008 R2 64位系统杀毒软件
查看>>
git直接提交删除的文件方法(附脚本)
查看>>
我的友情链接
查看>>
netty学习笔记
查看>>
更改win7文件类型默认操作
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
Webgoat 笔记总结 Web Services
查看>>
jquery easyui 阶段总结
查看>>
Linux Mysql安装部署
查看>>
多线程 概述
查看>>
Nagios达到阈值时发不出告警邮件问题总结
查看>>
Linux IPTABLES 防火墙的设定
查看>>
shell 学习笔记(17)
查看>>
数据仓库架构演进与菜鸟实时数据仓库设计
查看>>
我的友情链接
查看>>
互联网公司应该要有的技术人员配置和开发事项清单
查看>>