Client
socketio.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Socket.io Demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.js"></script>
<script>
const socket = io('http://127.0.0.1:3000', {
query: {
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImlkIjoxNDM0LCJvcGVyYXRvcl9pZCI6IjE0MzQ4NjMiLCJ1c2VybmFtZSI6ImxiX2FkbWluIiwibmlja25hbWUiOiIiLCJnYW1ldHlwZSI6ImxpdmUiLCJ0eXBlIjoxLCJtdXRlIjpmYWxzZX0sImlhdCI6MTY5MzMwMjczNywiZXhwIjoxNjkzMzA5OTM3fQ.9mj9jTj5XV37Wd5PSN8U_3fAgtHSy7ZYZMoUhlIvut0",
},
transports: ['websocket']
});
socket.on('connect', () => {
console.log('已連接到伺服器');
});
socket.on('chat', (msg) => {
console.log(msg)
document.getElementById('output').innerHTML += '<br>' + msg;
});
function sendMessage() {
const message = document.getElementById('inputMessage').value;
socket.emit('send_message', message);
}
</script>
</head>
<body>
<h2>Socket.io</h2>
<input type="text" id="inputMessage" placeholder="輸入消息">
<button onclick="sendMessage()">發送消息</button>
<div id="output"></div>
</body>
</html>
Server
開一個資料夾取名叫 Server[命名隨意]
將 server.js 放置其中
server.js
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// 當有新的客戶端連接時
io.on('connection', (socket) => {
console.log('一位用戶已連接');
const jsonArray = [
{
"username": "johnDoe",
"accept-type": "credit-card",
"amount": 100.50,
"remark": "Payment for invoice #1234",
"trans_room_id": "113001"
},
{
"username": "janeSmith",
"accept-type": "paypal",
"amount": 250.00,
"remark": "Refund for order #5678",
"trans_room_id": "113001"
},
{
"username": "aliceWong",
"accept-type": "bank-transfer",
"amount": 500.75,
"remark": "Monthly subscription",
"trans_room_id": "113001"
}
];
//nsp.to(`otc_lobbylist`).emit('lobbylist', `{"command":"6601","data":` + JSON.stringify(JSON.stringify(jsonArray)) + `}`);
io.emit('chat', `{"command":"6601","data":` + JSON.stringify(JSON.stringify(jsonArray)) + `}` );
// 接收 'send_message' 事件並發送給所有用戶
socket.on('send_message', (message) => {
io.emit('chat', message);
});
socket.on('disconnect', () => {
console.log('一位用戶已斷線');
});
});
// 伺服器啟動
const PORT = 3000;
server.listen(PORT, () => {
console.log(`伺服器正在運行於 http://localhost:${PORT}`);
});
執行命令
npm init -y
npm install express socket.io