一、聊天需求

实现聊天的功能,一对一、多对多
image.png

二、需求分析

明白需求的意义,明确自己要做的事情

三、设计

数据库设计

接口设计

技术选型:websocket

四、编码-后端

SpringBoot整合WebSocket,实现聊天服务器
实现步骤:
1.依赖jar

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>

2.编写配置文件类

  1. @Configuration
  2. public class WebSocketConfig {
  3. @Bean
  4. public ServerEndpointExporter createSEE(){
  5. return new ServerEndpointExporter();
  6. }
  7. }

3.实现服务器类

  1. @Component
  2. @Scope(scopeName = "prototype")
  3. @ServerEndpoint("/chat/server/{nickname}")
  4. public class ChatServer {
  5. private String nickname;//用户的昵称
  6. private Session session;//会话对象
  7. public static ConcurrentHashMap<String,Session> users=new ConcurrentHashMap<>();//记录当前用户
  8. @OnOpen //连接-服务端
  9. public void open(@PathParam("nickname") String name,Session session){
  10. if(users.contains(name)){
  11. //昵称已占用
  12. sendMsg(session,"亲,昵称已被占用!");
  13. }else {
  14. this.nickname=name;
  15. this.session=session;
  16. users.put(name,session);
  17. sendMoreMsg("欢迎 "+name+" 进入聊天区!");
  18. }
  19. }
  20. @OnMessage //监听 消息,接收消息
  21. public void message(String msg,Session session){
  22. System.err.println("服务端接收:"+msg);
  23. sendMsg(session,"已收到,时间-"+System.currentTimeMillis());
  24. sendMoreMsg(nickname+"-说:"+msg);
  25. }
  26. @OnError //异常监听,只要出错误
  27. public void error(Throwable throwable){
  28. System.err.println("出错了");
  29. }
  30. @OnClose //监听关闭
  31. public void close(Session session){
  32. users.remove(nickname);//移除
  33. sendMoreMsg("让我们掌声欢送 "+nickname+" 的离开!");
  34. }
  35. //发送单挑消息
  36. private void sendMsg(Session session,String msg){
  37. try {
  38. //发送消息
  39. session.getBasicRemote().sendText(msg);
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. //群发消息
  45. private static void sendMoreMsg(String msg){
  46. try {
  47. //发送消息
  48. for(String s:users.keySet()){
  49. users.get(s).getBasicRemote().sendText(msg);
  50. }
  51. } catch (IOException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55. //推送消息
  56. public static boolean pushMsg(String msg){
  57. sendMoreMsg(msg);
  58. return true;
  59. }
  60. }

测试截图:
image.png

五、编码-前端

绘制聊天页面,实现websocket的调用
image.png
参考代码:

  1. <template>
  2. <div>
  3. <!-- 1.连接 -->
  4. <div>
  5. <van-cell-group inset>
  6. <van-field
  7. v-model="nickname"
  8. center
  9. label-width="50px"
  10. clearable
  11. label="昵称"
  12. placeholder="请输入昵称"
  13. >
  14. <template #button>
  15. <van-button size="small" type="primary" @click="joinRoom()">连接</van-button>
  16. <van-button size="small" style="margin-left: 10px;" type="info" @click="exitRoom()">退出</van-button>
  17. </template>
  18. </van-field>
  19. </van-cell-group>
  20. </div>
  21. <!-- 2.聊天信息 -->
  22. <div>
  23. <van-cell v-for="item in msgs" :key="item" :title="item" />
  24. </div>
  25. <!-- 3.发送消息 -->
  26. <div style="position: absolute; bottom: 37px;width: 100%;">
  27. <van-cell-group inset>
  28. <van-field
  29. v-model="msg"
  30. center
  31. clearable
  32. placeholder="请输入聊天信息"
  33. >
  34. <template #button>
  35. <van-button size="small" type="primary" @click="sendMsg()">发送</van-button>
  36. </template>
  37. </van-field>
  38. </van-cell-group>
  39. </div>
  40. </div>
  41. </template>
  42. <script>
  43. export default{
  44. data(){
  45. return{
  46. nickname:"",
  47. msg:"",
  48. msgs:[
  49. "测试01"
  50. ],
  51. ws:{}
  52. }
  53. },
  54. methods:{
  55. joinRoom(){
  56. if ('WebSocket' in window){
  57. //完成实例化
  58. this.ws = new WebSocket("ws://localhost:9999/chat/server/"+this.nickname);
  59. //监听消息接收
  60. this.ws.onmessage = (res=>{
  61. console.log("数据已接收...",res.data);
  62. this.msgs.push(res.data);
  63. });
  64. //连接服务器
  65. this.ws.onopen=(res=>{
  66. this.msgs.push("加入成功");
  67. });
  68. }
  69. },
  70. exitRoom(){
  71. console.log("退出");
  72. this.ws.close();
  73. this.msgs.push("退出聊天室");
  74. this.nickname="";
  75. },
  76. sendMsg(){//发送聊天消息
  77. this.ws.send(this.msg);//发送消息
  78. this.msgs.push("我说:"+this.msg);
  79. this.msg="";
  80. }
  81. }
  82. }
  83. </script>
  84. <style>
  85. </style>