WebSocket+Express讓前後端一家親

因為不想廢話,這裡就不解釋什麼是WebSocket了XD,進入正題

這裡直接使用Github上的websockets/ws項目,它直接使用了express做為項目,所以我們也一起跟著用吧XD

連結在這 https://github.com/websockets/ws

這裡我只寫我做的結果,所有的內容會放到github上,也會給上連接

Server的code

建立server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//import express 和 ws 套件
const express = require('express')
const WebSocket = require('ws')

//指定開啟的 port
const PORT = 3000
const WSS_PORT = 8080

//創建 express 的物件,並綁定及監聽 3000 port ,且設定開啟後在 console 中提示
const app = express()

const path = require('path')

const {
v4: uuidv4
} = require('uuid')

app.engine('.html', require('ejs').__express);

// Optional since express defaults to CWD/views

app.set('views', path.join(__dirname, 'views'));

// Path to our public directory

app.use(express.static(path.join(__dirname, 'public')));

// Without this you would need to
// supply the extension to res.render()
// ex: res.render('users.html').
app.set('view engine', 'html')

app.get('/', function(req, res) {
res.send('Hello WebSocket')
});

// Dummy users
var users = [{
name: 'tobi',
email: 'tobi@gmail.com'
},
{
name: 'loki',
email: 'loki@gmail.com'
},
{
name: 'jane',
email: 'jane@gmail.com'
}
];

app.get('/users', function(req, res) {
res.render('index', {
users: users,
title: "users example",
header: "Dummy users"
})
});

app.listen(PORT, () => {
console.log(`Express started on port ${PORT}`)
})

const wss = new WebSocket.Server({
port: WSS_PORT
});

wss.on('connection', function connection(ws) {

ws.on('message', function incoming(message) {
console.log('client send: %s', message)
});

setInterval(() => {

var uuid = uuidv4()
ws.send(uuid);
console.log('server send: %s', uuid)

}, 1000)

});

假裝Server有一直在傳輸信息所以使用setInterval 代替 

Client的code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>WebSockets</title>
</head>

<body onload="onload()">

<h1>Hello WebSockets</h1>

</body>

<style>
body {
background-color: lightblue;
overflow: auto;
}
</style>

<script>
function onload() {

let ws = new WebSocket('ws://localhost:8080')
ws.onopen = () => {
console.log('open connection')
}
ws.onclose = () => {
console.log('close connection')
}
ws.onmessage = event => {
console.log('client收到server信息')
console.log(event.data)
var msg = document.createElement('div')
msg.innerHTML = event.data;
document.querySelector('body').append(msg);
msg.focus();

}

}
</script>

</html>

執行server.js查看效果

Server console

Client page

Client console

完整的項目在這

https://github.com/cn27529/express-ws

收工

參考自

https://letswrite.tw/websocket/

https://medium.com/enjoy-life-enjoy-coding/javaScript-websocket-讓前後端沒有距離

Copyright © Bruce Huang All rights reserved.