使用websocket做一个及时通讯功能————02完成服务端在线聊天功能

版权声明:欢迎转载,欢迎技术交流,转载声明出处即可@@ https://blog.csdn.net/qq_36389107/article/details/80329619

1.创建程序

打开idea输入 new project————>spring Initializr——>next 然后写入如下内容
这里写图片描述
接着 next 选择 core里面的lombok及web模块的 websocket 然后next——>finishj即可

2.创建文件

1.先在pom里面引入fastJson,代码如下

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

之后创建文件如下图所示
这里写图片描述
附上代码
(1) ChatController

package com.vic.chat.chatbase.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vic.chat.chatbase.util.WebSocketUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;

@ServerEndpoint(value = "/webSocket/{userId}")
@Component
public class ChatController {
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) {
        WebSocketUtils.put(userId, session);
    }
    @OnMessage
    public void onMessage(String message) throws IOException {

        JSONObject bean = JSON.parseObject(message);
        broadcast((String)bean.get("msg"), (String)bean.get("from"),(String)bean.get("to"));
    }
    @OnError
    public void onError(@PathParam("userId") String userId, Throwable t) {
        WebSocketUtils.remove(userId);
    }
    @OnClose
    public void onClose(@PathParam("userId") String userId) {
        WebSocketUtils.remove(userId);
    }

    /**
     * 发送消息
     * @param message
     * @param from
     * @param to
     */
    private void broadcast(String message, String from, String to) {
        if ("-1".equals(to)) {
            List<Session> sessions = WebSocketUtils.getOtherSession(from);
            if (sessions.size() > 0) {
                for (Session s : sessions) {
                    s.getAsyncRemote().sendText(message);
                }
            }
        } else {
            Session session = WebSocketUtils.get(to);
            if (null != session && session.isOpen()) {
                session.getAsyncRemote().sendText(message);
            } else {
                Session self = WebSocketUtils.get(from);
                self.getAsyncRemote().sendText("对方已下线");
            }
        }
    }
}

(2) LoginController

package com.vic.chat.chatbase.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class LoginController {
    private static Map<Integer,String> map = new ConcurrentHashMap<>();
    @PostMapping("/login")
    public Map<String,Object> login(Integer id){
        Map<Integer,String> allMap=new ConcurrentHashMap<>();
        allMap.put(1,"http://images.hanjiapz.com/upload/20171022/25e112639794494897e1e4478fa1c95fjpg?imageslim");
        allMap.put(2,"http://images.hanjiapz.com/upload/20171104/5e2184f0bea2428b9a336d77f5ddec3cjpg?imageslim");
        allMap.put(3,"http://ounwl7hpu.bkt.clouddn.com/upload/20170930/c4aa3f029cf1491e9bcf310868781abc");
        allMap.put(4,"http://ounwl7hpu.bkt.clouddn.com/upload/20170901/9ee5503a838b4dbbad2fad15019e19b8");
        allMap.put(5,"http://ounwl7hpu.bkt.clouddn.com/upload/20170819/a2c01030181142e387e81ab5e7b3b702");
        allMap.put(6,"http://ounwl7hpu.bkt.clouddn.com/upload/20170819/a2c01030181142e387e81ab5e7b3b702");
        allMap.put(7,"http://images.hanjiapz.com/upload/20171031/7d369c76c5034ee1a6e57974b920f3a0jpg?imageslim");
        allMap.put(8,"http://ounwl7hpu.bkt.clouddn.com/upload/20170818/d2b7f76ffd854f688ffef48886af54d6");
        String header=allMap.get(id);
        String header2=map.get(id);
        Map<String,Object> result=new HashMap<>();
        result.put("code",500);
        result.put("msg","账号不存在");
        if (header!=null&&header2!=null){
            result.put("msg","账号已经登陆了");
        }
        if(header!=null&&header2==null){
            map.put(id,header);
            result.put("code",200);
            result.put("msg",header);
        }
        return result;
    }
    @PostMapping("/logout")
    public Map<String,Object> logout(Integer id){
        String header=map.get(id);
        Map<String,Object> result=new HashMap<>();
        result.put("code",500);
        if (header!=null){
            map.remove(id);
            result.put("code",200);
        }
        return result;
    }
}

(3)ChatConfig

package com.vic.chat.chatbase.util;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class ChatConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

(4)WebSocketUtils

package com.vic.chat.chatbase.util;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketUtils {
    private static Map<String,Session> map = new ConcurrentHashMap<>();
    private static final String PREFIX="mws";
    public static void put(String userid,Session session){
        map.put(getKey(userid),session);
    }
    public static Session get(String userid){
        return map.get(getKey(userid));
    }
    public static List<Session> getOtherSession(String userid){
        List<Session> result = new ArrayList<>();
        Set<Map.Entry<String, Session>> set=  map.entrySet();
        for(Map.Entry<String, Session> s:set){
            if(!s.getKey().equals(getKey(userid))){
                result.add(s.getValue());
            }
        }
        return result;
    }
    public static void remove(String userid){
        map.remove(getKey(userid));
    }
    public static boolean hasConnection(String userid){
        return map.containsKey(getKey(userid));
    }

    private static String getKey(String userid){
        return PREFIX+"_"+userid;
    }
}

(5)ChatBaseApplication

package com.vic.chat.chatbase;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ChatBaseApplication {

    public static void main(String[] args) {
        SpringApplication.run(ChatBaseApplication.class, args);
    }
}

好了,到此位置我们完成了一个简单的聊天系统的后端代码

3.代码逻辑理解

上面代码的逻辑是,通过LoginController 模拟登录。登陆之后,即可进行聊天,可以进行单聊和群聊。
下一步将会实现该代码的前端页面

猜你喜欢

转载自blog.csdn.net/qq_36389107/article/details/80329619