socket实现java聊天室,公告等功能,前后端分离(附源码)

 pom文件


       org.springframework.boot
       spring-boot-starter-websocket

 application.yml中端口设置

server:
  port: 11112

 

 下面是代码

package com.websocket.demo.websocket;

import org.junit.jupiter.api.Test;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lzy
 * @Date 2019/8/14 9:44
 * @Version 1.0
 * @name 创建处理器
 */
public class WebSocketPushHandler extends TextWebSocketHandler {
    private static final List USER_LIST = new ArrayList<>();

    /**
     * 用户进入系统监听
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("3.用户进入系统。。。");
        System.out.println("用户信息:" + session.getAttributes());
        Map map = session.getAttributes();
        for (String key : map.keySet()) {
            System.out.println("key:" + key + " and value:" + map.get(key));
        }
        USER_LIST.add(session);
    }

    /**
     * 处理用户请求
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("系统处理xxx用户的请求信息。。。");
        System.out.println("===>>> 当前系统用户数为:"+USER_LIST.size());
        System.out.println("用户所发送消息为:"+message.getPayload() );
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("----------------"+ LocalTime.now() +"----------------");
        stringBuilder.append("

当前系统在线用户数为:"+USER_LIST.size()+"



"); stringBuilder.append("

用户"+session.getAttributes().get("userId")+":


"); stringBuilder.append("
"+message.getPayload()+"

"); TextMessage textMessage = new TextMessage(stringBuilder.toString()); //向所有用户广播消息 sendMessagesToUsers(textMessage); } /** * 用户退出后的处理 */ @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { if (session.isOpen()) { session.close(); } System.out.println("===>>> 退出系统时用户数为:"+USER_LIST.size()); USER_LIST.remove(session); System.out.println(session.getAttributes().get("userId")+"xxx用户退出系统。。。"); } /** * 自定义函数 * 给所有的在线用户发送消息 */ public static void sendMessagesToUsers(TextMessage message) { for (WebSocketSession user : USER_LIST) { try { // isOpen()在线就发送 if (user.isOpen()) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder .append("########################################
") .append("    ").append(LocalDateTime.now()).append("
") .append("[用户]
") .append(message.getPayload()).append("
") .append("########################################
"); TextMessage textMessage = new TextMessage(stringBuilder); user.sendMessage(textMessage); } } catch (IOException e) { e.printStackTrace(); System.out.println(e.getLocalizedMessage()); } } } /** * 自定义函数 * 发送消息给指定的在线用户 */ public static void sendMessageToUser(String userId, TextMessage message) { for (WebSocketSession user : USER_LIST) { if (user.getAttributes().get("userId").equals(userId)) { try { // isOpen()在线就发送 if (user.isOpen()) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder .append("########################################
") .append("    ").append(LocalDateTime.now()).append("
") .append("[用户]
") .append(message.getPayload()).append("
") .append("########################################
"); TextMessage textMessage = new TextMessage(stringBuilder); user.sendMessage(textMessage); } } catch (IOException e) { e.printStackTrace(); System.out.println(e.getLocalizedMessage()); } } } } @Test public void Test(List USER_LIST){ for (WebSocketSession user : USER_LIST) { System.out.println(user); } } }
package com.websocket.demo.websocket;

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 java.util.Map;

/**
 * @author lzy
 * @Date 2019/8/14 9:41
 * @Version 1.0
 * @name 创建握手 此类用来获取登录用户信息并交由websocket管理
 * @Description HandshakeInterceptor WebSocket握手请求的拦截器. 检查握手请求和响应, 对WebSocketHandler传递属性
 */
public class MyWebSocketInterceptor implements HandshakeInterceptor {

    /**
     * 在握手之前执行该方法, 继续握手返回true, 中断握手返回false. 通过attributes参数设置WebSocketSession的属性
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map attributes) throws Exception {
        System.out.println("1.用户建立连接。。。");
        if (request instanceof ServletServerHttpRequest) {
            String userId = ((ServletServerHttpRequest) request).getServletRequest().getParameter("userId");
            attributes.put("userId", userId);
            System.out.println("用户唯一标识:" + userId);
        }
        return true;
    }

    /**
     * 在握手之后执行该方法. 无论是否握手成功都指明了响应状态码和相应头.
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,Exception exception) {
        System.out.println("2.在握手之后执行该方法. 无论是否握手成功都指明了响应状态码和相应头");
    }
}
package com.websocket.demo.config;

import com.websocket.demo.websocket.MyWebSocketInterceptor;
import com.websocket.demo.websocket.WebSocketPushHandler;
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;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * @author lzy
 * @Date 2019/8/14 9:47
 * @Version 1.0
 * @name websocket配置类
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig  implements WebSocketConfigurer {
    /**
     * 注册WebSocket处理类
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        System.out.println("注册WebSocket处理类");
        registry.addHandler(createWebSocketPushHandler(), "/webSocketServer")
                .addInterceptors(createHhandshakeInterceptor()).setAllowedOrigins("*");
        registry.addHandler(createWebSocketPushHandler(), "/sockjs/webSocketServer")
                .addInterceptors(createHhandshakeInterceptor()).withSockJS();
    }

    /**
     *
     * @Title: createHhandshakeInterceptor
     * @Description: 握手拦截器
     * @return
     */
    @Bean
    public HandshakeInterceptor createHhandshakeInterceptor() {
        System.out.println("握手拦截器");
        return new MyWebSocketInterceptor();
    }

    /**
     *
     * @Title: createWebSocketPushHandler
     * @Description: 处理类
     * @return
     */
    @Bean
    public WebSocketHandler createWebSocketPushHandler() {
        System.out.println("处理类");
        return new WebSocketPushHandler();
    }
}
package com.websocket.demo.controller;

import com.websocket.demo.websocket.WebSocketPushHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

/**
 * @author lzy
 * @Date 2019/8/14 14:51
 * @Version 1.0
 * @name
 */
@RestController
@RequestMapping("/msg")
public class MsgController {

    /**
     * 功能描述:向全体广播消息
     * @param: [msg] 消息内容
     * @return: boolean
     * @auther: lzy
     * @date: 2019/8/14 16:10
     */
    @PostMapping("/sendMsg")
    public boolean sendMsg(String msg){
        System.out.println("全体广播消息 ["+msg+"]");
        TextMessage textMessage = new TextMessage(msg);
        try{
            WebSocketPushHandler.sendMessagesToUsers(textMessage);
        }catch (Exception e){
            return false;
        }
        return true;
    }

    /**
     * 功能描述:向指定用户发送消息
     * @param msg 消息内容
     * @param userId 用户编号
     * @return: boolean
     * @auther: lzy
     * @date: 2019/8/14 16:13
     */
    @PostMapping("/sendMsgByUser")
    public boolean sendMsgByUser(String msg,String userId){
        System.out.println("向 "+userId+" 发送消息,消息内容为:"+msg);
        TextMessage textMessage = new TextMessage(msg);
        try{
            WebSocketPushHandler.sendMessageToUser(userId,textMessage);
        }catch (Exception e){
            return false;
        }
        return true;
    }
}

页面代码 




    
    Java后端WebSocket的Tomcat实现


Welcome


源码下载链接:https://download.csdn.net/download/qq_39187822/11546600

你可能感兴趣的:(java)