---
# System prepended metadata

title: Socket Services 如何使用
tags: [' Talk', Templates]

---

---
title: Socket Services 如何使用
tags: Templates, Talk
description: View the slide with "Slide Mode".
---

# Socket Services 如何使用!

>製作Tinn
>參考:Google各位大大
>[範例參考詳解](https://socket.io/) 
---

## 目的

透過 Websocket Services 進行廣播、前後端即時傳遞訊息

---


 ## Usage flow

```graphviz
digraph graph_name{
    rankdir=LR
    bgcolor="transparent"
    
 Backend[shape=box,fontsize=22]   WebsocketService[shape=circle, fontcolor=red,fontsize=24]
    "Backend"->WebsocketService[label=API]
    
WebsocketService->{Frontend_All, Frontend_Dept,Frontend_Group,Frontend_UserA,Frontend_UserB}

Frontend_All[fontsize=20]
Frontend_Dept[fontsize=20]
Frontend_Group[fontsize=20]
Frontend_UserA[fontsize=20]
Frontend_UserB[fontsize=20]
    
}
```

---

## 初始化
- 使用 socket.io
- 定義監聽事件
---

```javascript=
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>


let socket = io('http://localhost:7777');

socket.on('connect', function() {

    //監聽全部
    socket.on('bck_ybweb', function(data) {
        console.log(data, '全體廣播')
    })
    
    //監聽個人 `${companyCode_systemCode_account}`
    socket.on('bck_ybweb_20181201', function(data) {
        console.log(data, '個人廣播')
    })
    
    //監聽部門 `${companyCode_systemCode_deptId}`
    socket.on('bck_ybweb_18', function(data) {
        console.log(data, '部門廣播')
    })
    
    //監聽群組 `${companyCode_systemCode_groupId}`
    socket.on('bck_ybweb_18_6', function(data) {
        console.log(data, '部門群組廣播')
    })
    
    //監聽踢出事件
    socket.on('kickout', function(data) {
        // alert('您被登出')
        //call logout api
        window.location.href = "about:blank";
        window.close();
    })
    
    //連線時向WebsocketService告知（可有可無）
    socket.emit('join', {
        userName: '松庭',
        companyCode: 'bck',
        systemCode: 'ybweb',
        deptId: 18,
        groupId: 6,
        account: 20181201,
        socketId: socket.id,
        connected_on: new Date()
    });
})
```

### Vue.js
```shell=
npm install socket.io-client
```
```typescript=
import io from 'socket.io-client'
```

```typescript=

this.companyCode = 'bck' //公司代號
this.systemCode = 'ybweb' //專案代號
this.deptId = 18 //部門id
this.groupId = 6 //組別id
this.account = 20181201 //員編

this.host = 'http://example.socket/65535'
 io(this.host).on('connect', () => {
 
 //監聽全部
    io.on('bck_ybweb', (data) {
        console.log(data, '全體廣播')
    })
    
    //監聽個人 `${companyCode_systemCode_account}`
    io.on('bck_ybweb_20181201', (data) {
        console.log(data, '個人廣播')
    })
    
    //監聽部門 `${companyCode_systemCode_deptId}`
    io.on('bck_ybweb_18', (data) {
        console.log(data, '部門廣播')
    })
    
    //監聽群組 `${companyCode_systemCode_groupId}`
    io.on('bck_ybweb_18_6', (data) {
        console.log(data, '部門群組廣播')
    })
    
    //監聽踢出事件
    io.on('kickout', (data) {
        // alert('您被登出')
        //call logout api
        window.location.href = "about:blank";
        window.close();
    })
    
    //連線時向WebsocketService告知（可有可無）
    io.emit('join', {
        userName: '松庭',
        companyCode: 'bck',
        systemCode: 'ybweb',
        deptId: 18,
        groupId: 6,
        account: 20181201,
        socketId: socket.id,
        connected_on: new Date()
    });
 })
```
---
## API requests
```
Content-Type : application/json
```
```
POST /api/notify/:apiKey' //請先索取專案對應的apiKey
```
### input parameters

```json=
{
    "companyCode": "bck",
    "systemCode": "ybweb",
    "deptId": 18,
    "groupId": 6,
    "account": "20181201"
    "action": "message",
    "data": "hello"
}
```

### 欄位說明

-  ```companyCode``` (Require|String): 公司別代碼
    
- ```systemCode``` (Require|String): 專案代碼
- ```deptId``` (Nullable): 部門id
- ```groupId``` (Nullable): 群組id
- ```account``` (Nullable): 員工編號
- ```action``` (Require|in: message, permission): 動作

- ```data``` : 傳送訊息的內容

```
action 只能填寫 message 或 permission
```

```
groupId 有填寫時 depId 不得為空
```

### Output:
#### success response :
```
Http statusCode : 200
```
```json=
{
    "message": "ok"
}
```

#### error response :
```
Http statusCode : 400
```
```json=
{
  "errorMessage": "後端給的錯誤訊息"
}
```
### Demo
---

<img src="https://i.imgur.com/IJMDIH2.gif">

---

### 進階- 確認前端是否收到消息 

[DEMO 效果 請看這裡 ](https://i.imgur.com/t90bPkR.gif)

[socket.emit vs io.emit 說明](https://stackoverflow.com/questions/32674391/io-emit-vs-socket-emit/32675498)
```javascript=
// Backend
// 注意這裡使用的 'emit' 必須為 'socket' 不是外層的 'io'
// 否則會提示錯誤訊息 Callbacks are not supported when broadcasting at Socket.emit

io.on('connection', (socket) => {
    socket.emit('events', 'hungry', (callback) => {
    //callback 數據將被 'yes' 
        if(callback){
            dosomething......
        }
    });
});

//Frontend
socket.on('connect', () => {
    socket.on('events', (msg, fn) => {
        fn('yes')
        console.log(msg) // hungry
    });
});
```
