Browse Source

websocket长连接接收消息。

jiaxiaoqiang 8 months ago
parent
commit
867c7f8821

+ 83 - 21
entry/src/main/ets/common/component/TitleStateComp.ets

@@ -12,6 +12,9 @@ import appRecovery from '@ohos.app.ability.appRecovery';
 import AbilityStage from '@ohos.app.ability.AbilityStage';
 import wantAgent from '@ohos.app.ability.wantAgent'
 import Want from '@ohos.app.ability.Want'
+import socketService, { MessageInfoModel } from '../util/SocketService'
+import JGRequest from '../util/request/Request'
+import RequestParamModel from '../../viewmodel/RequestParamModel'
 
 /*
  * 顶部状态栏
@@ -43,15 +46,28 @@ export struct TitleStateComp {
       this.isClick = !this.isClick
     }
   })
-  // 消息弹窗控制器
-  noticeDialogController: CustomDialogController = new CustomDialogController({
-    builder: NoticeDialog({}),
-    alignment: DialogAlignment.Center,
-    customStyle: true,
-    cancel: () => {
-      this.isClick = !this.isClick
-    }
-  })
+  // websocket 相关  =============
+  creatWebsocket = () => {
+
+    socketService.connect()
+
+    socketService.registerMessageListener(async (data: Object) => {
+      console.log("WebSocketDemo callback", JSON.stringify(data))
+      this.getMessageList()
+      // "{\"content\":[{\"content\":\"工单:09.24.0019 工位:生产准备工位-2 呼叫工序: 检测的物料\",\"created\":\"2024-08-23 15:43:22\",\"creator\":\"admin\",\"deptId\":\"1\",\"id\":\"98\",\"msgId\":\"1\",\"orgId\":\"1\",\"state\":\"1\",\"title\":\"工位呼叫齐套物料\",\"type\":\"1\",\"updated\":\"2024-08-23 15:43:22\",\"updator\":\"admin\",\"userId\":28}],\"msgType\":\"1\"}"
+    })
+  }
+  @State messageInfoList: MessageInfoModel[] = []
+  getMessageList = async () => {
+    this.messageInfoList = []
+    let res: MessageInfoModel = await JGRequest.post("/api/v1/sys/message/userMessage", {
+      pageNo: 1,
+      pageSize: 30,
+    } as RequestParamModel)
+    this.messageInfoList = res.records ?? []
+    console.log("WebSocketDemo list", JSON.stringify(this.messageInfoList))
+    this.noticeDialogController.open()
+  }
 
   aboutToAppear(): void {
     ////生产操作
@@ -63,8 +79,30 @@ export struct TitleStateComp {
       this.kittingNum = res.kittingNum
       this.planNum = res.planNum
     })
+
+    this.creatWebsocket()
   }
 
+  setMessageRead = async (m: MessageInfoModel, index: number) => {
+    let res: MessageInfoModel = await JGRequest.post("/api/v1/sys/message/confirmMessage", [m.id] as string[])
+    let temp = m
+    temp.readState = "1"
+    this.messageInfoList[index] = temp
+
+  }
+  // 消息弹窗控制器
+  noticeDialogController: CustomDialogController = new CustomDialogController({
+    builder: NoticeDialog({
+      messages: this.messageInfoList,
+      setRead: this.setMessageRead
+    }),
+    alignment: DialogAlignment.Center,
+    customStyle: true,
+    cancel: () => {
+      this.isClick = !this.isClick
+    }
+  })
+
   build() {
     Stack() {
       Text()
@@ -132,7 +170,8 @@ export struct TitleStateComp {
             // router.pushUrl({
             //  // url:"pages/OutboundStation"
             // })
-            this.noticeDialogController.open()
+            this.getMessageList()
+
           })
 
           Row() {
@@ -448,7 +487,9 @@ struct shutdown {
 @CustomDialog
 struct NoticeDialog {
   controller: CustomDialogController
-  Notices: NoticeInfo[] = []
+  @Prop messages: MessageInfoModel[]
+  setRead: (item: MessageInfoModel, index: number) => void = (item: MessageInfoModel, index: number) => {
+  }
 
   build() {
     Column({ space: 10 }) {
@@ -462,35 +503,56 @@ struct NoticeDialog {
 
       Row() {
         List() {
-          ForEach(this.Notices, (item: NoticeInfo) => {
+          ForEach(this.messages, (item: MessageInfoModel, index: number) => {
             ListItem() {
-              Row() {
-                Text(item.Notice)
-                  .fontSize($r('app.float.fontSize_38'))
+              Column() {
+                Text(item.title)
+                  .fontSize($r('app.float.fontSize_24'))
                   .fontColor($r('app.color.general_font_color'))
                   .opacity($r('app.float.general_font_opacity'))
-                Text(item.NoticeDate)
-                  .fontSize($r('app.float.fontSize_38'))
+                Text(item.content)
+                  .fontSize($r('app.float.fontSize_20'))
+                  .fontColor($r('app.color.general_font_color'))
+                  .opacity($r('app.float.general_font_opacity'))
+                Text("来自: " + item?.creator ?? "" + item.readState!)
+                  .fontSize($r('app.float.fontSize_20'))
+                  .fontColor($r('app.color.general_font_color'))
+                  .opacity($r('app.float.card_font_default_opacity'))
+
+                Text(item.created)
+                  .fontSize($r('app.float.fontSize_20'))
                   .fontColor($r('app.color.general_font_color'))
                   .opacity($r('app.float.card_font_default_opacity'))
               }
-              .justifyContent(FlexAlign.SpaceBetween)
+              .justifyContent(FlexAlign.Start)
+              .alignItems(HorizontalAlign.Start)
               .width('100%')
+              .margin({ bottom: 10 })
+              .backgroundColor(item.readState == "1" ? $r("app.color.green_100") : $r("app.color.gray_6666"))
+              .padding(6)
+              .borderRadius($r('app.float.notice_size'))
+              .onClick(() => {
+                if (this.setRead) {
+                  this.setRead(item, index)
+
+                }
+              })
+
             }
           })
         }
       }
-      .width('90%')
+      .width('98%')
       .height('80%')
       .alignItems(VerticalAlign.Top)
       .borderRadius($r('app.float.notice_size'))
       .borderWidth($r('app.float.general_border_width'))
       .borderColor($r('app.color.general_border_color'))
     }
-    .width('45%')
+    .width('50%')
     .height('70%')
     .justifyContent(FlexAlign.Center)
-    .backgroundColor($r('app.color.page_general_background'))
+    .backgroundColor(Color.White)
     .borderRadius($r('app.float.notice_size'))
   }
 }

+ 148 - 0
entry/src/main/ets/common/util/SocketService.ets

@@ -0,0 +1,148 @@
+import webSocket from '@ohos.net.webSocket';
+import { BusinessError } from '@ohos.base';
+import CommonConstants from '../constants/CommonConstants';
+
+
+const TAG = "WebSocketDemo"
+
+type MessageCallback = (data: Object) => void;
+
+
+export interface MessageInfoModel {
+  pageNo?: number
+  pageSize?: number
+  content?: string
+  created?: string
+  creator?: string
+  deptId?: string
+  id?: string
+  msgId?: string
+  orgId?: string
+  readState?: string
+  receiveUsers?: string
+  state?: string
+  title?: string
+  type?: string
+  updated?: string
+  updator?: string
+  userId?: string
+  records?: MessageInfoModel[]
+}
+
+export class SocketService {
+  private socket: webSocket.WebSocket = webSocket.createWebSocket();
+  private messageCallback: MessageCallback | null = null
+
+  constructor() {
+    // this.createWebSocket();
+    this.onOpen();
+    this.onMessage();
+    this.onClose();
+    this.onError();
+  }
+
+  /**
+   * 注册监听器,对服务端发送的消息进行处理
+   * @param messageListener
+   */
+  public registerMessageListener(messageCallback: MessageCallback) {
+    this.messageCallback = messageCallback;
+  }
+
+  /**
+   * 创建WebSocket对象,该对象负责有服务端进行通信
+   //  */
+  // private createWebSocket() {
+  //   console.info(TAG, "start create websocket");
+  //   this.socket =
+  //   console.info(TAG, "create socket sucess");
+  // }
+
+  /**
+   * 根据指定的url与服务器进行连接
+   * @param url 协议格式 ws://或wss://
+   */
+  public connect() {
+    let url = `ws://10.88.11.200:8079/websocket/${CommonConstants.AUTH_TOKEN}`
+    this.socket.connect(url)
+      .then((isConnect) => {
+        if (isConnect) {
+          console.info(TAG, "connect sucess");
+        }
+      })
+  }
+
+  /**
+   * 连接成功后,向服务端发送消息
+   * @param data
+   */
+  public sendMessage(data: string) {
+    this.socket.send(data)
+      .then((isSucess) => {
+        console.info(TAG, "send result:" + isSucess);
+        if (isSucess) {
+          console.info(TAG, "send message sucess")
+        }
+      })
+      .catch((e: BusinessError) => {
+        console.info(TAG, "send message fail:" + JSON.stringify(e))
+      })
+  }
+
+  /**
+   * 主动与服务器断开连接
+   */
+  public closeConnect() {
+    this.socket.close();
+  }
+
+  /**
+   * 监听连接打开的事件,当与服务端的连接打开时触发回调
+   *
+   *
+   */
+  private onOpen() {
+    this.socket.on("open", (err, data) => {
+      console.info(TAG, "on open status" + JSON.stringify(data));
+    })
+  }
+
+  /**
+   * 监听服务器发送消息的事件,当服务器向客户端发送消息时触发回调
+   *
+   */
+  private onMessage() {
+    this.socket.on("message", (err, data) => {
+      console.info(TAG, "receive from server:message is:" + JSON.stringify(data));
+      if (this.messageCallback) {
+        this.messageCallback(data);
+      }
+
+    })
+  }
+
+  /**
+   *
+   * 监听连接断开事件,当与服务器断开连接时触发回调
+   */
+  private onClose() {
+    this.socket.on("close", (err, data) => {
+      console.info(TAG, "on close :close code is:" + data.code + ",close reason is:" + data.reason);
+    })
+  }
+
+  /**
+   *监听err事件,只要在建立连接、发送数据等任意过程中发生错误,都会触发回调
+   *
+   */
+  private onError() {
+    this.socket.on("error", (data) => {
+      console.info(TAG, "on err :err is" + JSON.stringify(data));
+    })
+  }
+}
+
+
+let socketService = new SocketService();
+
+export default socketService

+ 4 - 4
entry/src/main/ets/pages/LoginPage.ets

@@ -18,8 +18,8 @@ struct LoginPage {
   controller: TextInputController = new TextInputController()
   //1是拣选,2是装配,3是测试,4是维修站,5是入库,6是出库
   @State stationDictValue: string = ''
-  @State loginName: string = 'JGtest-32'
-  @State password: string = 'admin@123'
+  @State loginName: string = 'XF-01'
+  @State password: string = '123456'
   @State dept: DeptInfo = { deptName: '仿真中心' }
   @State workstation: WorkstationInfo = {}
   @State productionLine: ProductionLine = { name: '仿真中心电装产线' }
@@ -117,7 +117,7 @@ struct LoginPage {
         CommonConstants.STATION_IP = user.stationIp!
       }
       if (CommonConstants.AUTH_TOKEN && CommonConstants.AUTH_TOKEN.length > 0) {
-        if (CommonConstants.stationDictValue === '5') {
+        if (CommonConstants.stationDictValue === '6') {
           router.pushUrl({
             url: 'pages/Warehousing',
             params: {
@@ -126,7 +126,7 @@ struct LoginPage {
               stationId: CommonConstants.STATION_NANE as WorkstationInfo
             }
           })
-        } else if (CommonConstants.stationDictValue === '6') {
+        } else if (CommonConstants.stationDictValue === '5') {
           router.pushUrl({
             url: 'pages/OutboundStation',
             params: {

+ 10 - 2
entry/src/main/resources/base/element/font_size.json

@@ -33,11 +33,11 @@
       "value": "16fp"
     },
     {
-      "name":"process_card_middle_font_size",
+      "name": "process_card_middle_font_size",
       "value": "16fp"
     },
     {
-      "name":"process_card_large_font_size",
+      "name": "process_card_large_font_size",
       "value": "25.3fp"
     },
     {
@@ -57,6 +57,14 @@
       "value": "20fp"
     },
     {
+      "name": "fontSize_18",
+      "value": "14fp"
+    },
+    {
+      "name": "fontSize_16",
+      "value": "12fp"
+    },
+    {
       "name": "fontSize_14",
       "value": "9.3fp"
     },