# Socket.io 介紹
### 老闆來點寇汀吧!
### 20180524
https://socket.io/
https://www.facebook.com/bosscodingplease/
---
## 介紹
----
很多.io的即時遊戲都是用socket.io做的~
Agar.io
![](https://i.imgur.com/vulnFUW.png)
---
## 大概原理-廣播der感覺
![](https://i.imgur.com/OsWWrFa.png)
---
## 優點
* 簡化溝通-像js一樣接收事件on
* 可以非常即時的同步
* 可以在執行階段保存資料
---
## 最近案例
![](https://i.imgur.com/bkqe6e7.png)
http://techart.nthu.edu.tw/THE2018/#/
----
影片:
https://www.facebook.com/1944000092504903/videos/2055063868065191/
---
## LiveCoding
server
```
npm i socket.io express -s
```
```javascript=
var fs = require('fs')
//https的一些設定
var options = {
key: fs.readFileSync('/etc/letsencrypt/live/awiclass.monoame.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/awiclass.monoame.com/fullchain.pem')
}
//https & socket port
var https = require('https').createServer(options);
https.listen(4040)
var io = require('socket.io')(https);
console.log("Server socket 4040 , api 4000")
//api port
var app = require('express')();
var port = 4000;
app.listen(port, function(){
console.log('API listening on *:' + port);
});
var messages = [];
//用api方式取得
app.get('/api/messages',function(req,res){
res.send(messages);
})
io.on('connection', function(socket){
//初始化...
console.log("A user connected.");
io.emit("allMessage",messages);
socket.on('sendMessage',function(obj){
//get all message!
messages.push(obj);
console.log( obj.message + " - " + obj.name )
io.emit('newMessage', obj);
})
})
```
----
client端
* 建立socket
* 監聽或觸發事件
```javascript=
socket = io("https://awiclass.monoame.com:4040")
```
https://codepen.io/frank890417/pen/XqwxaN?editors=1100
```javascript=
this.socket.emit("sendMessage", someobj...)
this.socket.on("allMessage",obj=>{
///.....
})
```
---
## 掛載:pm2套件
```linux
sudo apt get pm2
pm2 start xxx.js
pm2 kill //關閉全部
```
---
## 開心睡覺?
{"metaMigratedAt":"2023-06-14T16:36:44.348Z","metaMigratedFrom":"Content","title":"Socket.io 介紹","breaks":true,"contributors":"[]"}