WebSocket+Express讓前後端一家親

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

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

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

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

Server的code

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


<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>

執行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-讓前後端沒有距離


沒有留言: