Ver3.0 ๐ ์์ฉํ๋ก๊ทธ๋๋ฐ์์ ์ค์๊ฐ ๋ฐ์ดํฐ ์๊ฐํ ๊ตฌํํ๊ธฐ - ๋ฐ์ดํฐ๋ฅผ ์ด์ ์จ์ฌ๊ฒ ๋ง๋๋ ๊ธฐ์

๐ ์์ฉํ๋ก๊ทธ๋๋ฐ์์ ์ค์๊ฐ ๋ฐ์ดํฐ ์๊ฐํ ๊ตฌํํ๊ธฐ - ๋ฐ์ดํฐ๋ฅผ ์ด์ ์จ์ฌ๊ฒ ๋ง๋๋ ๊ธฐ์
์ค์๊ฐ์ผ๋ก ๋ณํํ๋ ๋ฐ์ดํฐ๋ฅผ ๋์์์ ํ์ธํ๋ ์ง๋ฆฟํจ, ์ง๊ธ ๋ฐ๋ก ์์ํด๋ณผ๊น์? ๐ซ
๐ฏ ์ค์๊ฐ ๋ฐ์ดํฐ ์๊ฐํ, ์ ์ด๋ ๊ฒ ํซํ ๊ฑฐ์ผ?
์์ฆ ๊ฐ๋ฐ์๋ค ์ฌ์ด์์ ์ค์๊ฐ ๋ฐ์ดํฐ ์๊ฐํ๊ฐ ์ง์ง ๋์ธ๋๋ผ๊ณ ์ ใ ใ ใ ์ฃผ์ ์ฐจํธ ๋ณด๋ฉด์ ์ค์๊ฐ์ผ๋ก ๋ง ์์ง์ด๋ ๊ฑฐ ๋ณด๋ฉด ์ฌ์ฅ์ด ์ซ๊นํด์ง์์์? ๊ทธ๊ฒ ๋ฐ๋ก ์ค์๊ฐ ๋ฐ์ดํฐ ์๊ฐํ์ ๋งค๋ ฅ์ด์์! ๐
๊ทผ๋ฐ ์ด๊ฒ ๋จ์ํ ๋ฉ์์ด ๋ณด์ด๋ ค๊ณ ํ๋ ๊ฒ ์๋๋ผ, ์ค์ ๋ก ์์ฒญ๋ ๋น์ฆ๋์ค ๊ฐ์น๋ฅผ ๋ง๋ค์ด๋ด๊ฑฐ๋ ์. ์๋ฒ ๋ชจ๋ํฐ๋ง, ์ฃผ์ ๊ฑฐ๋, IoT ์ผ์ ๋ฐ์ดํฐ, ์์ ๋ฏธ๋์ด ํธ๋ ๋ ๋ถ์ ๋ฑ๋ฑ... ๋ฐ์ดํฐ๊ฐ ์ค์๊ฐ์ผ๋ก ๋ณํ๋ ๋ชจ๋ ๊ณณ์์ ํ์ํ ๊ธฐ์ ์ด์์.
๐ก ์ค์๊ฐ ์๊ฐํ๊ฐ ํ์ํ ๋ํ์ ์ธ ๋ถ์ผ๋ค
โข ๊ธ์ต ๊ฑฐ๋ ์์คํ
- ์ฃผ์, ์ํธํํ ์ฐจํธ
โข ์๋ฒ/๋คํธ์ํฌ ๋ชจ๋ํฐ๋ง - CPU, ๋ฉ๋ชจ๋ฆฌ, ํธ๋ํฝ
โข IoT ๋๋ฐ์ด์ค ๊ด๋ฆฌ - ์ผ์ ๋ฐ์ดํฐ, ์จ๋, ์ต๋
โข ๊ฒ์ ๋์๋ณด๋ - ์ค์๊ฐ ํ๋ ์ด์ด ํต๊ณ
โข ์์
๋ฏธ๋์ด ๋ถ์ - ํธ๋ ๋, ๊ฐ์ฑ ๋ถ์
โข ๋ฌผ๋ฅ/๋ฐฐ์ก ์ถ์ - ์ค์๊ฐ ์์น ์ ๋ณด
๐ ์ค์๊ฐ ํต์ ๋ฐฉ์ - ์ด๋ค ๊ฑธ ์ ํํ ๊น?
์ค์๊ฐ ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ๋ ๋ฐฉ๋ฒ์ ์๊ฐ๋ณด๋ค ๋ค์ํด์. ๊ฐ๊ฐ ์ฅ๋จ์ ์ด ์์ด์ ์ํฉ์ ๋ง๊ฒ ๊ณจ๋ผ ์จ์ผ ํ๋๋ฐ, ์ด๊ฒ ์ง์ง ์ค์ํ๊ฑฐ๋ ์ ใ ใ ์๋ชป ์ ํํ๋ฉด ๋์ค์ ๋ฆฌํฉํ ๋ง ์ง์ฅ์ ๊ฒฝํํ ์๋...
1๏ธโฃ WebSocket - ์๋ฐฉํฅ ํต์ ์ ์์๋
WebSocket์ ์ค์๊ฐ ํต์ ์ ์ ๋๊ฐ์์์. HTTP์ ๋ฌ๋ฆฌ ํ ๋ฒ ์ฐ๊ฒฐํ๋ฉด ๊ณ์ ์ฐ๊ฒฐ ์ํ๋ฅผ ์ ์งํ๋ฉด์ ์๋ฒ์ ํด๋ผ์ด์ธํธ๊ฐ ์์ ๋กญ๊ฒ ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ์ ์ ์์ด์.
โจ WebSocket์ ์ฅ์
โข ๋ฎ์ ๋ ์ดํด์ - ์ฐ๊ฒฐ ์ ์ง๋ก ์ค๋ฒํค๋ ์ต์ํ
โข ์๋ฐฉํฅ ํต์ - ์๋ฒ์์๋ ํด๋ผ์ด์ธํธ๋ก ํธ์ ๊ฐ๋ฅ
โข ํจ์จ์ ์ธ ๋์ญํญ ์ฌ์ฉ - ํค๋ ์ค๋ฒํค๋๊ฐ ์ ์
โข ์ค์๊ฐ์ฑ ๋ณด์ฅ - ์ฆ๊ฐ์ ์ธ ๋ฐ์ดํฐ ์ ์ก
๊ธฐ๋ณธ์ ์ธ WebSocket ๊ตฌํ ์ฝ๋๋ฅผ ๋ณผ๊น์?
// ํด๋ผ์ด์ธํธ ์ธก (JavaScript)
const socket = new WebSocket('ws://localhost:8080/realtime');
socket.onopen = function(event) {
console.log('WebSocket ์ฐ๊ฒฐ ์ฑ๊ณต! ๐');
socket.send(JSON.stringify({ type: 'subscribe', channel: 'stock-data' }));
};
socket.onmessage = function(event) {
const data = JSON.parse(event.data);
updateChart(data); // ์ฐจํธ ์
๋ฐ์ดํธ ํจ์ ํธ์ถ
};
socket.onerror = function(error) {
console.error('WebSocket ์๋ฌ ๋ฐ์:', error);
};
socket.onclose = function(event) {
console.log('์ฐ๊ฒฐ ์ข
๋ฃ๋จ. ์ฌ์ฐ๊ฒฐ ์๋ ์ค...');
setTimeout(() => reconnect(), 3000);
};
// ์๋ฒ ์ธก (Node.js + ws ๋ผ์ด๋ธ๋ฌ๋ฆฌ)
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
console.log('์๋ก์ด ํด๋ผ์ด์ธํธ ์ฐ๊ฒฐ๋จ');
// 1์ด๋ง๋ค ๋๋ค ๋ฐ์ดํฐ ์ ์ก
const interval = setInterval(() => {
const data = {
timestamp: Date.now(),
value: Math.random() * 100,
symbol: 'AAPL'
};
ws.send(JSON.stringify(data));
}, 1000);
ws.on('close', () => {
clearInterval(interval);
console.log('ํด๋ผ์ด์ธํธ ์ฐ๊ฒฐ ์ข
๋ฃ');
});
});
2๏ธโฃ Server-Sent Events (SSE) - ๋จ๋ฐฉํฅ์ ์ฌํํจ
SSE๋ ์๋ฒ์์ ํด๋ผ์ด์ธํธ๋ก๋ง ๋ฐ์ดํฐ๋ฅผ ๋ณด๋ด๋ ๋จ๋ฐฉํฅ ํต์ ์ด์์. WebSocket๋ณด๋ค ๊ฐ๋จํ์ง๋ง, ์๋ฒ ํธ์๋ง ํ์ํ ๊ฒฝ์ฐ์ ์ถฉ๋ถํ ๊ฐ๋ ฅํด์!
๐ฏ SSE๋ฅผ ์ ํํด์ผ ํ๋ ๊ฒฝ์ฐ
โข ์๋ฒ์์ ํด๋ผ์ด์ธํธ๋ก๋ง ๋ฐ์ดํฐ ์ ์ก์ด ํ์ํ ๋
โข ์๋ ์ฌ์ฐ๊ฒฐ ๊ธฐ๋ฅ์ด ํ์ํ ๋
โข HTTP/2๋ฅผ ํ์ฉํ๊ณ ์ถ์ ๋
โข ๊ตฌํ์ด ๊ฐ๋จํด์ผ ํ ๋
// ํด๋ผ์ด์ธํธ ์ธก
const eventSource = new EventSource('/api/realtime-data');
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log('์ ๋ฐ์ดํฐ ๋์ฐฉ:', data);
updateVisualization(data);
};
eventSource.onerror = function(error) {
console.error('SSE ์๋ฌ:', error);
// ์๋์ผ๋ก ์ฌ์ฐ๊ฒฐ ์๋ํจ
};
// ์๋ฒ ์ธก (Express.js)
app.get('/api/realtime-data', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const sendData = () => {
const data = {
timestamp: Date.now(),
temperature: 20 + Math.random() * 10,
humidity: 40 + Math.random() * 20
};
res.write(`data: ${JSON.stringify(data)}\n\n`);
};
const interval = setInterval(sendData, 2000);
req.on('close', () => {
clearInterval(interval);
});
});
3๏ธโฃ Long Polling - ๊ตฌ์์ด์ง๋ง ํธํ์ฑ ๊ฐ
Long Polling์ ์ข ์๋ ๋ฐฉ์์ด๊ธด ํ๋ฐ, ๋ ๊ฑฐ์ ๋ธ๋ผ์ฐ์ ์ง์์ด ํ์ํ๊ฑฐ๋ ๋ฐฉํ๋ฒฝ ์ด์๊ฐ ์์ ๋ ์ ์ฉํด์ ใ ใ
// ํด๋ผ์ด์ธํธ ์ธก Long Polling
function longPoll() {
fetch('/api/poll-data')
.then(response => response.json())
.then(data => {
updateChart(data);
longPoll(); // ์ฆ์ ๋ค์ ์์ฒญ
})
.catch(error => {
console.error('Polling ์๋ฌ:', error);
setTimeout(longPoll, 5000); // ์๋ฌ ์ 5์ด ํ ์ฌ์๋
});
}
longPoll(); // ์์
| ํต์ ๋ฐฉ์ | ์ฅ์ | ๋จ์ | ์ ํฉํ ์ํฉ |
|---|---|---|---|
| WebSocket | ์๋ฐฉํฅ, ๋ฎ์ ์ง์ฐ, ํจ์จ์ | ๊ตฌํ ๋ณต์ก๋, ํ๋ก์ ์ด์ | ์ฑํ , ๊ฒ์, ์ค์๊ฐ ํ์ |
| SSE | ๊ฐ๋จํ ๊ตฌํ, ์๋ ์ฌ์ฐ๊ฒฐ | ๋จ๋ฐฉํฅ, IE ๋ฏธ์ง์ | ์๋ฆผ, ํผ๋, ๋ชจ๋ํฐ๋ง |
| Long Polling | ๋์ ํธํ์ฑ, ๋ฐฉํ๋ฒฝ ํต๊ณผ | ๋์ ์ค๋ฒํค๋, ๋นํจ์จ์ | ๋ ๊ฑฐ์ ์ง์ ํ์์ |
| Short Polling | ๊ตฌํ ๋งค์ฐ ๊ฐ๋จ | ๋งค์ฐ ๋นํจ์จ์ , ์๋ฒ ๋ถํ | ์ค์๊ฐ์ฑ ๋ฎ์๋ ๋ ๋ |
๐ ์๊ฐํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ ํ ๊ฐ์ด๋
์ค์๊ฐ ๋ฐ์ดํฐ๋ฅผ ๋ฐ์์ผ๋ฉด ์ด์ ์์๊ฒ ๋ณด์ฌ์ค์ผ๊ฒ ์ฃ ? ์๊ฐํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ ํ์ด ์ง์ง ์ค์ํ๋ฐ, ๊ฐ์ ํน์ง์ด ํ์คํด์ ์ฉ๋์ ๋ง๊ฒ ๊ณจ๋ผ์ผ ํด์ ใ ใ ใ
๐จ Chart.js - ์ ๋ฌธ์์ ๋ฒ ํ
Chart.js๋ ์ ๋ง ์ฝ๊ณ ์ง๊ด์ ์ด์์. ๋ฌธ์๋ ์ ๋์ด ์๊ณ , ์ปค๋ฎค๋ํฐ๋ ํ๋ฐํด์ ์ฒ์ ์์ํ๊ธฐ ๋ฑ ์ข์์. ์ค์๊ฐ ์ ๋ฐ์ดํธ๋ ๊ฐ๋จํ๊ฒ ๊ตฌํํ ์ ์์ด์!
// Chart.js๋ก ์ค์๊ฐ ์ฐจํธ ๋ง๋ค๊ธฐ
const ctx = document.getElementById('myChart').getContext('2d');
const chart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: '์ค์๊ฐ ์จ๋',
data: [],
borderColor: 'rgb(102, 126, 234)',
backgroundColor: 'rgba(102, 126, 234, 0.1)',
tension: 0.4
}]
},
options: {
responsive: true,
animation: {
duration: 750 // ๋ถ๋๋ฌ์ด ์ ๋๋ฉ์ด์
},
scales: {
y: {
beginAtZero: true
}
}
}
});
// ์ค์๊ฐ ๋ฐ์ดํฐ ์ถ๊ฐ ํจ์
function addData(label, data) {
chart.data.labels.push(label);
chart.data.datasets[0].data.push(data);
// ์ต๋ 20๊ฐ ๋ฐ์ดํฐ๋ง ์ ์ง
if (chart.data.labels.length > 20) {
chart.data.labels.shift();
chart.data.datasets[0].data.shift();
}
chart.update('none'); // ์ ๋๋ฉ์ด์
์์ด ์ฆ์ ์
๋ฐ์ดํธ
}
// WebSocket์ผ๋ก ๋ฐ์ ๋ฐ์ดํฐ ์ฒ๋ฆฌ
socket.onmessage = function(event) {
const data = JSON.parse(event.data);
const time = new Date(data.timestamp).toLocaleTimeString();
addData(time, data.temperature);
};
๐ก Chart.js ์ค์๊ฐ ์ต์ ํ ํ
โข update('none') ์ฌ์ฉ์ผ๋ก ์ ๋๋ฉ์ด์
์คํต
โข ๋ฐ์ดํฐ ํฌ์ธํธ ๊ฐ์ ์ ํ (20~50๊ฐ ๊ถ์ฅ)
โข decimation ํ๋ฌ๊ทธ์ธ์ผ๋ก ๋ฐ์ดํฐ ๊ฐ์ํ
โข responsive: true๋ก ๋ฐ์ํ ๋์
๐ D3.js - ์ปค์คํฐ๋ง์ด์ง์ ์
D3.js๋ ์ง์ง ์์ ๋๊ฐ ๋์์. ์ํ๋ ๋๋ก ๋ญ๋ ์ง ๋ง๋ค ์ ์๋๋ฐ, ๊ทธ๋งํผ ๋ฌ๋์ปค๋ธ๊ฐ ์์ฃ ใ ใ ํ์ง๋ง ๋ณต์กํ ์ธํฐ๋์ ์ด๋ ๋ ํนํ ์๊ฐํ๊ฐ ํ์ํ๋ฉด D3๊ฐ ๋ต์ด์์!
// D3.js๋ก ์ค์๊ฐ ๋ผ์ธ ์ฐจํธ
const margin = {top: 20, right: 30, bottom: 30, left: 40};
const width = 800 - margin.left - margin.right;
const height = 400 - margin.top - margin.bottom;
const svg = d3.select("#chart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
let data = [];
const maxDataPoints = 50;
// ์ค์ผ์ผ ์ค์
const x = d3.scaleTime().range([0, width]);
const y = d3.scaleLinear().range([height, 0]);
// ๋ผ์ธ ์์ฑ๊ธฐ
const line = d3.line()
.x(d => x(d.time))
.y(d => y(d.value))
.curve(d3.curveMonotoneX);
// ์ถ ์ถ๊ฐ
const xAxis = svg.append("g")
.attr("transform", `translate(0,${height})`);
const yAxis = svg.append("g");
// ๋ผ์ธ ํจ์ค
const path = svg.append("path")
.attr("fill", "none")
.attr("stroke", "#667eea")
.attr("stroke-width", 2);
// ์ค์๊ฐ ์
๋ฐ์ดํธ ํจ์
function updateChart(newValue) {
data.push({
time: new Date(),
value: newValue
});
if (data.length > maxDataPoints) {
data.shift();
}
// ์ค์ผ์ผ ์
๋ฐ์ดํธ
x.domain(d3.extent(data, d => d.time));
y.domain([0, d3.max(data, d => d.value)]);
// ์ถ ์
๋ฐ์ดํธ
xAxis.transition().duration(500).call(d3.axisBottom(x));
yAxis.transition().duration(500).call(d3.axisLeft(y));
// ๋ผ์ธ ์
๋ฐ์ดํธ
path.datum(data)
.transition()
.duration(500)
.attr("d", line);
}
โก Apache ECharts - ์ฑ๋ฅ ๊ดด๋ฌผ
ECharts๋ ์ค๊ตญ์์ ๋ง๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ธ๋ฐ, ์ฑ๋ฅ์ด ์ง์ง ๋ฏธ์ณค์ด์ ใ ใ ใ ๋์ฉ๋ ๋ฐ์ดํฐ๋ ๊ฑฐ๋ฌํ๊ณ , ์ฐจํธ ์ข ๋ฅ๋ ์์ฒญ ๋ง์์. ์ต๊ทผ์ ์ธ๊ธฐ ๊ธ์์น ์ค!
// ECharts ์ค์๊ฐ ์ฐจํธ
const myChart = echarts.init(document.getElementById('main'));
const option = {
title: {
text: '์ค์๊ฐ ์๋ฒ ๋ชจ๋ํฐ๋ง'
},
tooltip: {
trigger: 'axis'
},
xAxis: {
type: 'category',
data: []
},
yAxis: {
type: 'value',
name: 'CPU ์ฌ์ฉ๋ฅ (%)'
},
series: [{
name: 'CPU',
type: 'line',
smooth: true,
data: [],
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
offset: 0,
color: 'rgba(102, 126, 234, 0.5)'
}, {
offset: 1,
color: 'rgba(102, 126, 234, 0.1)'
}])
}
}]
};
myChart.setOption(option);
// ์ค์๊ฐ ๋ฐ์ดํฐ ์ถ๊ฐ
function addRealtimeData(timestamp, value) {
option.xAxis.data.push(timestamp);
option.series[0].data.push(value);
// ์ต๋ 30๊ฐ ์ ์ง
if (option.xAxis.data.length > 30) {
option.xAxis.data.shift();
option.series[0].data.shift();
}
myChart.setOption(option);
}
| ๋ผ์ด๋ธ๋ฌ๋ฆฌ | ๋์ด๋ | ์ฑ๋ฅ | ์ปค์คํฐ๋ง์ด์ง | ์ถ์ฒ ์ฉ๋ |
|---|---|---|---|---|
| Chart.js | โญ ์ฌ์ | โญโญโญ ๋ณดํต | โญโญ ์ ํ์ | ๊ฐ๋จํ ๋์๋ณด๋, ํ๋กํ ํ์ |
| D3.js | โญโญโญโญโญ ์ด๋ ค์ | โญโญโญโญ ์ข์ | โญโญโญโญโญ ๋ฌดํ | ๋ณต์กํ ์ธํฐ๋์ , ๋ ํนํ ์๊ฐํ |
| ECharts | โญโญ ๋ณดํต | โญโญโญโญโญ ์ต๊ณ | โญโญโญโญ ๋์ | ๋์ฉ๋ ๋ฐ์ดํฐ, ์ํฐํ๋ผ์ด์ฆ |
| Plotly.js | โญโญ ๋ณดํต | โญโญโญ ๋ณดํต | โญโญโญ ๋ณดํต | ๊ณผํ/ํต๊ณ ์๊ฐํ |
| Highcharts | โญโญ ๋ณดํต | โญโญโญโญ ์ข์ | โญโญโญ ๋ณดํต | ์์ ์ฉ ํ๋ก์ ํธ (์ ๋ฃ) |
โ๏ธ ์ฑ๋ฅ ์ต์ ํ - ๋๊น ์๋ ์ค์๊ฐ ๊ฒฝํ ๋ง๋ค๊ธฐ
์ค์๊ฐ ์๊ฐํ์์ ์ฑ๋ฅ์ ์ง์ง ์๋ช ์ด์์! ๋ฐ์ดํฐ๊ฐ ๋ง ์์์ง๋๋ฐ ํ๋ฉด์ด ๋ฒ๋ฒ ๊ฑฐ๋ฆฌ๋ฉด... ์ฌ์ฉ์๋ค์ด ๋ฐ๋ก ์ดํํ๊ฑฐ๋ ์ ใ ใ ์ฑ๋ฅ ์ต์ ํ ๊ฟํ๋ค์ ๊ณต์ ํ ๊ฒ์!
๐ฏ ๋ฐ์ดํฐ ์ํ๋ง๊ณผ ์ง๊ณ
์ด๋น 100๊ฐ์ฉ ๋ฐ์ดํฐ๊ฐ ๋ค์ด์ค๋๋ฐ ์ ๋ถ ๋ค ๊ทธ๋ฆด ํ์๋ ์์์์? ์ ์ ํ ์ํ๋ง์ด ํต์ฌ์ด์์!
// ๋ฐ์ดํฐ ์ํ๋ง ํด๋์ค
class DataSampler {
constructor(maxPoints = 50) {
this.maxPoints = maxPoints;
this.buffer = [];
this.lastUpdate = Date.now();
this.updateInterval = 100; // 100ms๋ง๋ค ์
๋ฐ์ดํธ
}
addData(value) {
this.buffer.push({
timestamp: Date.now(),
value: value
});
// ๋ฒํผ๊ฐ ๋๋ฌด ํฌ๋ฉด ์ค๋๋ ๋ฐ์ดํฐ ์ ๊ฑฐ
if (this.buffer.length > this.maxPoints * 2) {
this.buffer = this.buffer.slice(-this.maxPoints);
}
}
getSampledData() {
const now = Date.now();
if (now - this.lastUpdate < this.updateInterval) {
return null; // ์์ง ์
๋ฐ์ดํธ ์๊ฐ ์๋
}
this.lastUpdate = now;
if (this.buffer.length <= this.maxPoints) {
return this.buffer;
}
// ๊ท ๋ฑ ์ํ๋ง
const step = this.buffer.length / this.maxPoints;
const sampled = [];
for (let i = 0; i < this.maxPoints; i++) {
const index = Math.floor(i * step);
sampled.push(this.buffer[index]);
}
return sampled;
}
// ์๊ฐ ๊ธฐ๋ฐ ์ง๊ณ (1์ด ๋จ์ ํ๊ท )
getAggregatedData(intervalMs = 1000) {
const aggregated = [];
const buckets = new Map();
this.buffer.forEach(item => {
const bucketKey = Math.floor(item.timestamp / intervalMs) * intervalMs;
if (!buckets.has(bucketKey)) {
buckets.set(bucketKey, []);
}
buckets.get(bucketKey).push(item.value);
});
buckets.forEach((values, timestamp) => {
const avg = values.reduce((a, b) => a + b, 0) / values.length;
aggregated.push({ timestamp, value: avg });
});
return aggregated;
}
}
// ์ฌ์ฉ ์์
const sampler = new DataSampler(50);
socket.onmessage = function(event) {
const data = JSON.parse(event.data);
sampler.addData(data.value);
};
// ์ฃผ๊ธฐ์ ์ผ๋ก ์ฐจํธ ์
๋ฐ์ดํธ
setInterval(() => {
const sampledData = sampler.getSampledData();
if (sampledData) {
updateChart(sampledData);
}
}, 100);
๐ requestAnimationFrame ํ์ฉ
๋ธ๋ผ์ฐ์ ์ ๋ฆฌํ์ธํธ ์ฃผ๊ธฐ์ ๋ง์ถฐ์ ์ ๋ฐ์ดํธํ๋ฉด ํจ์ฌ ๋ถ๋๋ฌ์์! requestAnimationFrame์ ํ์ฉํ๋ฉด 60fps๋ก ๋งค๋๋ฝ๊ฒ ๋ ๋๋งํ ์ ์์ด์.
// RAF๋ฅผ ํ์ฉํ ๋ถ๋๋ฌ์ด ์ ๋๋ฉ์ด์
class SmoothChart {
constructor(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.dataQueue = [];
this.currentData = [];
this.isAnimating = false;
this.maxPoints = 100;
}
addData(value) {
this.dataQueue.push(value);
if (!this.isAnimating) {
this.startAnimation();
}
}
startAnimation() {
this.isAnimating = true;
this.animate();
}
animate() {
// ํ์์ ๋ฐ์ดํฐ ๊ฐ์ ธ์ค๊ธฐ
while (this.dataQueue.length > 0) {
this.currentData.push(this.dataQueue.shift());
if (this.currentData.length > this.maxPoints) {
this.currentData.shift();
}
}
// ์บ๋ฒ์ค ํด๋ฆฌ์ด
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
// ์ฐจํธ ๊ทธ๋ฆฌ๊ธฐ
this.drawChart();
// ๋ค์ ํ๋ ์ ์์ฝ
if (this.dataQueue.length > 0 || this.isAnimating) {
requestAnimationFrame(() => this.animate());
} else {
this.isAnimating = false;
}
}
drawChart() {
const width = this.canvas.width;
const height = this.canvas.height;
const step = width / this.maxPoints;
this.ctx.beginPath();
this.ctx.strokeStyle = '#667eea';
this.ctx.lineWidth = 2;
this.currentData.forEach((value, index) => {
const x = index * step;
const y = height - (value / 100) * height;
if (index === 0) {
this.ctx.moveTo(x, y);
} else {
this.ctx.lineTo(x, y);
}
});
this.ctx.stroke();
}
}
๐พ Web Workers๋ก ๋ฐฑ๊ทธ๋ผ์ด๋ ์ฒ๋ฆฌ
๋ฌด๊ฑฐ์ด ๋ฐ์ดํฐ ์ฒ๋ฆฌ๋ Web Worker๋ก ๋ถ๋ฆฌํ๋ฉด ๋ฉ์ธ ์ค๋ ๋๊ฐ ์ ๋งํ์! UI๋ ๊ณ์ ๋ถ๋๋ฝ๊ฒ ์ ์ง๋๊ณ ์ ใ ใ
// worker.js - Web Worker ํ์ผ
self.onmessage = function(e) {
const { type, data } = e.data;
if (type === 'process') {
// ๋ณต์กํ ๋ฐ์ดํฐ ์ฒ๋ฆฌ
const processed = processLargeDataset(data);
self.postMessage({ type: 'result', data: processed });
}
};
function processLargeDataset(rawData) {
// ํต๊ณ ๊ณ์ฐ, ํํฐ๋ง, ๋ณํ ๋ฑ
const result = {
average: calculateAverage(rawData),
trend: calculateTrend(rawData),
anomalies: detectAnomalies(rawData)
};
return result;
}
function calculateAverage(data) {
return data.reduce((sum, val) => sum + val, 0) / data.length;
}
function calculateTrend(data) {
// ๊ฐ๋จํ ์ ํ ํ๊ท
const n = data.length;
let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
data.forEach((y, x) => {
sumX += x;
sumY += y;
sumXY += x * y;
sumX2 += x * x;
});
const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
return slope > 0 ? 'increasing' : 'decreasing';
}
function detectAnomalies(data) {
const mean = calculateAverage(data);
const stdDev = Math.sqrt(
data.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / data.length
);
return data.filter(val => Math.abs(val - mean) > 2 * stdDev);
}
// ๋ฉ์ธ ์ค๋ ๋์์ Worker ์ฌ์ฉ
const worker = new Worker('worker.js');
worker.onmessage = function(e) {
const { type, data } = e.data;
if (type === 'result') {
updateChartWithProcessedData(data);
}
};
// ๋์ฉ๋ ๋ฐ์ดํฐ ์ฒ๋ฆฌ ์์ฒญ
socket.onmessage = function(event) {
const rawData = JSON.parse(event.data);
worker.postMessage({ type: 'process', data: rawData });
};
โ ๏ธ ์ฑ๋ฅ ์ต์ ํ ์ฃผ์์ฌํญ
โข ๊ณผ๋ํ ์ต์ ํ๋ ์ฝ๋ ๋ณต์ก๋๋ฅผ ๋์ฌ์ - ํ์ํ ๋งํผ๋ง!
โข ๋ฉ๋ชจ๋ฆฌ ๋์ ์กฐ์ฌ - ์ด๋ฒคํธ ๋ฆฌ์ค๋ ์ ๋ฆฌ ํ์
โข ๋ชจ๋ฐ์ผ ํ๊ฒฝ ๊ณ ๋ ค - ๋ฐ์คํฌํฑ๋ณด๋ค ์ฑ๋ฅ ์ ์ฝ ํผ
โข ํ๋กํ์ผ๋ง ๋จผ์ - ์ถ์ธกํ์ง ๋ง๊ณ ์ธก์ ํ์ธ์!
๐ ๋ณด์๊ณผ ์์ ์ฑ - ์ค์ ๋ ธํ์ฐ
์ค์๊ฐ ์์คํ ์ ํญ์ ์ฐ๊ฒฐ๋์ด ์์ด์ ๋ณด์์ด ๋์ฑ ์ค์ํด์! ํ ๋ฒ ๋ซ๋ฆฌ๋ฉด ๊ณ์ ๋ฐ์ดํฐ๊ฐ ์๋๊ฐ ์ ์๊ฑฐ๋ ์ ใ ใ
๐ก๏ธ WebSocket ๋ณด์ ๊ฐํ
// ์์ ํ WebSocket ์ฐ๊ฒฐ ๊ตฌํ
class SecureWebSocket {
constructor(url, options = {}) {
this.url = url;
this.options = options;
this.ws = null;
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 5;
this.reconnectDelay = 1000;
this.heartbeatInterval = null;
}
connect() {
// WSS (WebSocket Secure) ์ฌ์ฉ
const token = this.getAuthToken();
const wsUrl = `${this.url}?token=${token}`;
this.ws = new WebSocket(wsUrl);
this.ws.onopen = () => {
console.log('๋ณด์ ์ฐ๊ฒฐ ์ฑ๊ณต โ
');
this.reconnectAttempts = 0;
this.startHeartbeat();
};
this.ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
// ๋ฉ์์ง ๊ฒ์ฆ
if (this.validateMessage(data)) {
this.handleMessage(data);
} else {
console.warn('์ ํจํ์ง ์์ ๋ฉ์์ง:', data);
}
} catch (error) {
console.error('๋ฉ์์ง ํ์ฑ ์๋ฌ:', error);
}
};
this.ws.onerror = (error) => {
console.error('WebSocket ์๋ฌ:', error);
};
this.ws.onclose = () => {
console.log('์ฐ๊ฒฐ ์ข
๋ฃ๋จ');
this.stopHeartbeat();
this.attemptReconnect();
};
}
getAuthToken() {
// JWT ํ ํฐ ๊ฐ์ ธ์ค๊ธฐ
return localStorage.getItem('auth_token') || '';
}
validateMessage(data) {
// ๋ฉ์์ง ๊ตฌ์กฐ ๊ฒ์ฆ
if (!data || typeof data !== 'object') return false;
if (!data.type || !data.timestamp) return false;
// ํ์์คํฌํ ๊ฒ์ฆ (5์ด ์ด๋ด)
const now = Date.now();
const messageTime = new Date(data.timestamp).getTime();
if (Math.abs(now - messageTime) > 5000) {
console.warn('์ค๋๋ ๋ฉ์์ง ๋ฌด์');
return false;
}
return true;
}
startHeartbeat() {
// 30์ด๋ง๋ค ํ ์ ์ก
this.heartbeatInterval = setInterval(() => {
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({ type: 'ping' }));
}
}, 30000);
}
stopHeartbeat() {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
}
}
attemptReconnect() {
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
console.error('์ต๋ ์ฌ์ฐ๊ฒฐ ์๋ ํ์ ์ด๊ณผ');
return;
}
this.reconnectAttempts++;
const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
console.log(`${delay}ms ํ ์ฌ์ฐ๊ฒฐ ์๋ (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
setTimeout(() => {
this.connect();
}, delay);
}
send(data) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
// ๋ฐ์ดํฐ ์ํธํ (ํ์์)
const encrypted = this.encryptData(data);
this.ws.send(JSON.stringify(encrypted));
} else {
console.warn('WebSocket์ด ์ฐ๊ฒฐ๋์ง ์์');
}
}
encryptData(data) {
// ์ค์ ํ๊ฒฝ์์๋ ์ ์ ํ ์ํธํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ฌ์ฉ
// ์: CryptoJS, Web Crypto API ๋ฑ
return {
...data,
timestamp: Date.now(),
checksum: this.calculateChecksum(data)
};
}
calculateChecksum(data) {
// ๊ฐ๋จํ ์ฒดํฌ์ฌ (์ค์ ๋ก๋ ๋ ๊ฐ๋ ฅํ ํด์ ์ฌ์ฉ)
return JSON.stringify(data).split('').reduce((a, b) => {
a = ((a << 5) - a) + b.charCodeAt(0);
return a & a;
}, 0);
}
handleMessage(data) {
// ๋ฉ์์ง ํ์
๋ณ ์ฒ๋ฆฌ
if (this.options.onMessage) {
this.options.onMessage(data);
}
}
close() {
this.stopHeartbeat();
if (this.ws) {
this.ws.close();
}
}
}
// ์ฌ์ฉ ์์
const secureWs = new SecureWebSocket('wss://api.example.com/realtime', {
onMessage: (data) => {
console.log('์์ ํ๊ฒ ์์ ๋ ๋ฐ์ดํฐ:', data);
updateVisualization(data);
}
});
secureWs.connect();
๐ ์๋ฒ ์ธก ๋ณด์ ๊ตฌํ
// Node.js + Express + ws ๋ณด์ ๊ตฌํ
const express = require('express');
const https = require('https');
const WebSocket = require('ws');
const jwt = require('jsonwebtoken');
const rateLimit = require('express-rate-limit');
const app = express();
// Rate Limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15๋ถ
max: 100 // ์ต๋ 100 ์์ฒญ
});
app.use(limiter);
// HTTPS ์๋ฒ ์์ฑ
const server = https.createServer({
cert: fs.readFileSync('cert.pem'),
key: fs.readFileSync('key.pem')
}, app);
const wss = new WebSocket.Server({
server,
verifyClient: (info, callback) => {
// ์ฐ๊ฒฐ ์ ์ธ์ฆ ๊ฒ์ฆ
const token = new URL(info.req.url, 'wss://localhost').searchParams.get('token');
if (!token) {
callback(false, 401, 'Unauthorized');
return;
}
jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) {
callback(false, 401, 'Invalid token');
} else {
info.req.user = decoded;
callback(true);
}
});
}
});
// ํด๋ผ์ด์ธํธ๋ณ ๋ฉ์์ง ์ ํ
const clientMessageLimits = new Map();
wss.on('connection', (ws, req) => {
const userId = req.user.id;
console.log(`์ฌ์ฉ์ ${userId} ์ฐ๊ฒฐ๋จ`);
// ๋ฉ์์ง ์นด์ดํฐ ์ด๊ธฐํ
clientMessageLimits.set(ws, {
count: 0,
resetTime: Date.now() + 60000 // 1๋ถ
});
ws.on('message', (message) => {
// Rate limiting ์ฒดํฌ
const limit = clientMessageLimits.get(ws);
const now = Date.now();
if (now > limit.resetTime) {
limit.count = 0;
limit.resetTime = now + 60000;
}
limit.count++;
if (limit.count > 60) { // ๋ถ๋น 60๊ฐ ์ ํ
ws.send(JSON.stringify({
type: 'error',
message: 'Rate limit exceeded'
}));
return;
}
try {
const data = JSON.parse(message);
// ์
๋ ฅ ๊ฒ์ฆ
if (!validateInput(data)) {
ws.send(JSON.stringify({
type: 'error',
message: 'Invalid input'
}));
return;
}
// ๋ฉ์์ง ์ฒ๋ฆฌ
handleClientMessage(ws, data, userId);
} catch (error) {
console.error('๋ฉ์์ง ์ฒ๋ฆฌ ์๋ฌ:', error);
}
});
ws.on('close', () => {
console.log(`์ฌ์ฉ์ ${userId} ์ฐ๊ฒฐ ์ข
๋ฃ`);
clientMessageLimits.delete(ws);
});
// ํ/ํ์ผ๋ก ์ฐ๊ฒฐ ์ ์ง ํ์ธ
ws.isAlive = true;
ws.on('pong', () => {
ws.isAlive = true;
});
});
// 30์ด๋ง๋ค ์ฐ๊ฒฐ ์ํ ํ์ธ
const interval = setInterval(() => {
wss.clients.forEach((ws) => {
if (ws.isAlive === false) {
return ws.terminate();
}
ws.isAlive = false;
ws.ping();
});
}, 30000);
wss.on('close', () => {
clearInterval(interval);
});
function validateInput(data) {
// ์
๋ ฅ ๊ฒ์ฆ ๋ก์ง
if (!data || typeof data !== 'object') return false;
if (typeof data.type !== 'string') return false;
if (data.type.length > 50) return false; // ํ์
๊ธธ์ด ์ ํ
// XSS ๋ฐฉ์ง
const dangerousPatterns = /<script|javascript:|onerror=/i;
const dataStr = JSON.stringify(data);
if (dangerousPatterns.test(dataStr)) return false;
return true;
}
function handleClientMessage(ws, data, userId) {
// ๊ถํ ์ฒดํฌ
if (!hasPermission(userId, data.type)) {
ws.send(JSON.stringify({
type: 'error',
message: 'Permission denied'
}));
return;
}
// ๋น์ฆ๋์ค ๋ก์ง ์ฒ๋ฆฌ
// ...
}
server.listen(8443, () => {
console.log('๋ณด์ WebSocket ์๋ฒ ์์: wss://localhost:8443');
});
๐ ๋ณด์ ์ฒดํฌ๋ฆฌ์คํธ
โ
WSS (WebSocket Secure) ์ฌ์ฉ - TLS/SSL ์ํธํ
โ
JWT ํ ํฐ ๊ธฐ๋ฐ ์ธ์ฆ
โ
Rate Limiting - DDoS ๋ฐฉ์ด
โ
์
๋ ฅ ๊ฒ์ฆ - XSS, Injection ๋ฐฉ์ง
โ
๋ฉ์์ง ํ์์คํฌํ ๊ฒ์ฆ
โ
์ฐ๊ฒฐ ์ํ ๋ชจ๋ํฐ๋ง (Heartbeat)
โ
์๋ฌ ํธ๋ค๋ง ๋ฐ ๋ก๊น
โ
CORS ์ ์ฑ
์ค์
๐จ ์ค์ ํ๋ก์ ํธ - ์ค์๊ฐ ์ฃผ์ ์ฐจํธ ๋ง๋ค๊ธฐ
์ด๋ก ๋ง ๋ฐฐ์ฐ๋ฉด ์ฌ๋ฏธ์์์์ ใ ใ ์ค์ ๋ก ๋์ํ๋ ์ค์๊ฐ ์ฃผ์ ์ฐจํธ๋ฅผ ๋ง๋ค์ด๋ณผ๊ฒ์! ์ด๊ฑฐ ์์ฑํ๋ฉด ํฌํธํด๋ฆฌ์ค์ ๋ฃ๊ธฐ ๋ฑ ์ข์์ ๐ช
๐ ํ๋ก์ ํธ ๊ตฌ์กฐ
realtime-stock-chart/
โโโ client/
โ โโโ index.html
โ โโโ app.js
โ โโโ styles.css
โโโ server/
โ โโโ server.js
โ โโโ stockData.js
โ โโโ websocket.js
โโโ package.json
โโโ README.md
๐ฅ๏ธ ํด๋ผ์ด์ธํธ ๊ตฌํ
<!-- index.html -->
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>์ค์๊ฐ ์ฃผ์ ์ฐจํธ</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<header>
<h1>๐ ์ค์๊ฐ ์ฃผ์ ๋ชจ๋ํฐ๋ง</h1>
<div class="status" id="status">์ฐ๊ฒฐ ์ค...</div>
</header>
<div class="stock-selector">
<button class="stock-btn active" data-symbol="AAPL">Apple</button>
<button class="stock-btn" data-symbol="GOOGL">Google</button>
<button class="stock-btn" data-symbol="MSFT">Microsoft</button>
<button class="stock-btn" data-symbol="TSLA">Tesla</button>
</div>
<div class="chart-container">
<canvas id="stockChart"></canvas>
</div>
<div class="stats-grid">
<div class="stat-card">
<div class="stat-label">ํ์ฌ๊ฐ</div>
<div class="stat-value" id="currentPrice">-</div>
</div>
<div class="stat-card">
<div class="stat-label">๋ณ๋๋ฅ </div>
<div class="stat-value" id="changePercent">-</div>
</div>
<div class="stat-card">
<div class="stat-label">๊ฑฐ๋๋</div>
<div class="stat-value" id="volume">-</div>
</div>
<div class="stat-card">
<div class="stat-label">์ต๊ณ ๊ฐ</div>
<div class="stat-value" id="highPrice">-</div>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
// app.js - ํด๋ผ์ด์ธํธ ๋ก์ง
class StockChartApp {
constructor() {
this.ws = null;
this.chart = null;
this.currentSymbol = 'AAPL';
this.maxDataPoints = 50;
this.data = {
labels: [],
prices: []
};
this.init();
}
init() {
this.setupChart();
this.connectWebSocket();
this.setupEventListeners();
}
setupChart() {
const ctx = document.getElementById('stockChart').getContext('2d');
this.chart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: '์ฃผ๊ฐ',
data: [],
borderColor: '#667eea',
backgroundColor: 'rgba(102, 126, 234, 0.1)',
borderWidth: 2,
tension: 0.4,
fill: true,
pointRadius: 0,
pointHoverRadius: 5
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
animation: {
duration: 0
},
scales: {
x: {
display: true,
grid: {
display: false
}
},
y: {
display: true,
grid: {
color: 'rgba(0, 0, 0, 0.05)'
}
}
},
plugins: {
legend: {
display: false
},
tooltip: {
mode: 'index',
intersect: false
}
},
interaction: {
mode: 'nearest',
axis: 'x',
intersect: false
}
}
});
}
connectWebSocket() {
const wsUrl = 'ws://localhost:8080';
this.ws = new WebSocket(wsUrl);
this.ws.onopen = () => {
console.log('WebSocket ์ฐ๊ฒฐ ์ฑ๊ณต! ๐');
this.updateStatus('์ฐ๊ฒฐ๋จ', 'connected');
this.subscribe(this.currentSymbol);
};
this.ws.onmessage = (event) => {
const data = JSON.parse(event.data);
this.handleStockData(data);
};
this.ws.onerror = (error) => {
console.error('WebSocket ์๋ฌ:', error);
this.updateStatus('์๋ฌ ๋ฐ์', 'error');
};
this.ws.onclose = () => {
console.log('WebSocket ์ฐ๊ฒฐ ์ข
๋ฃ');
this.updateStatus('์ฐ๊ฒฐ ๋๊น', 'disconnected');
// 3์ด ํ ์ฌ์ฐ๊ฒฐ ์๋
setTimeout(() => {
this.connectWebSocket();
}, 3000);
};
}
subscribe(symbol) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({
type: 'subscribe',
symbol: symbol
}));
// ๋ฐ์ดํฐ ์ด๊ธฐํ
this.data.labels = [];
this.data.prices = [];
this.chart.data.labels = [];
this.chart.data.datasets[0].data = [];
this.chart.update();
}
}
handleStockData(data) {
if (data.symbol !== this.currentSymbol) return;
const time = new Date(data.timestamp).toLocaleTimeString();
// ๋ฐ์ดํฐ ์ถ๊ฐ
this.data.labels.push(time);
this.data.prices.push(data.price);
// ์ต๋ ๊ฐ์ ์ ์ง
if (this.data.labels.length > this.maxDataPoints) {
this.data.labels.shift();
this.data.prices.shift();
}
// ์ฐจํธ ์
๋ฐ์ดํธ
this.chart.data.labels = this.data.labels;
this.chart.data.datasets[0].data = this.data.prices;
this.chart.update('none');
// ํต๊ณ ์
๋ฐ์ดํธ
this.updateStats(data);
}
updateStats(data) {
document.getElementById('currentPrice').textContent =
`$${data.price.toFixed(2)}`;
const changePercent = data.changePercent || 0;
const changeElem = document.getElementById('changePercent');
changeElem.textContent = `${changePercent > 0 ? '+' : ''}${changePercent.toFixed(2)}%`;
changeElem.style.color = changePercent >= 0 ? '#10b981' : '#ef4444';
document.getElementById('volume').textContent =
this.formatNumber(data.volume);
document.getElementById('highPrice').textContent =
`$${data.high.toFixed(2)}`;
}
updateStatus(text, status) {
const statusElem = document.getElementById('status');
statusElem.textContent = text;
statusElem.className = `status ${status}`;
}
formatNumber(num) {
if (num >= 1000000) {
return (num / 1000000).toFixed(1) + 'M';
} else if (num >= 1000) {
return (num / 1000).toFixed(1) + 'K';
}
return num.toString();
}
setupEventListeners() {
const buttons = document.querySelectorAll('.stock-btn');
buttons.forEach(btn => {
btn.addEventListener('click', () => {
// ํ์ฑ ๋ฒํผ ๋ณ๊ฒฝ
buttons.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
// ์ฌ๋ณผ ๋ณ๊ฒฝ
this.currentSymbol = btn.dataset.symbol;
this.subscribe(this.currentSymbol);
});
});
}
}
// ์ฑ ์์
const app = new StockChartApp();
โ๏ธ ์๋ฒ ๊ตฌํ
// server.js
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const path = require('path');
const StockDataGenerator = require('./stockData');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
// ์ ์ ํ์ผ ์ ๊ณต
app.use(express.static(path.join(__dirname, '../client')));
// ์ฃผ์ ๋ฐ์ดํฐ ์์ฑ๊ธฐ
const stockGenerator = new StockDataGenerator();
// WebSocket ์ฐ๊ฒฐ ๊ด๋ฆฌ
const clients = new Map();
wss.on('connection', (ws) => {
console.log('์ ํด๋ผ์ด์ธํธ ์ฐ๊ฒฐ๋จ');
const clientId = generateClientId();
clients.set(clientId, {
ws: ws,
subscriptions: new Set()
});
ws.on('message', (message) => {
try {
const data = JSON.parse(message);
handleClientMessage(clientId, data);
} catch (error) {
console.error('๋ฉ์์ง ํ์ฑ ์๋ฌ:', error);
}
});
ws.on('close', () => {
console.log('ํด๋ผ์ด์ธํธ ์ฐ๊ฒฐ ์ข
๋ฃ');
const client = clients.get(clientId);
if (client) {
client.subscriptions.forEach(symbol => {
stockGenerator.unsubscribe(symbol, clientId);
});
}
clients.delete(clientId);
});
});
function handleClientMessage(clientId, data) {
const client = clients.get(clientId);
if (!client) return;
if (data.type === 'subscribe') {
const symbol = data.symbol;
// ๊ธฐ์กด ๊ตฌ๋
์ทจ์
client.subscriptions.forEach(oldSymbol => {
stockGenerator.unsubscribe(oldSymbol, clientId);
});
client.subscriptions.clear();
// ์ ๊ตฌ๋
์ถ๊ฐ
client.subscriptions.add(symbol);
stockGenerator.subscribe(symbol, (stockData) => {
if (client.ws.readyState === WebSocket.OPEN) {
client.ws.send(JSON.stringify(stockData));
}
}, clientId);
console.log(`ํด๋ผ์ด์ธํธ ${clientId}๊ฐ ${symbol} ๊ตฌ๋
`);
}
}
function generateClientId() {
return Math.random().toString(36).substr(2, 9);
}
const PORT = process.env.PORT || 8080;
server.listen(PORT, () => {
console.log(`์๋ฒ ์์: http://localhost:${PORT}`);
});
// stockData.js - ์ฃผ์ ๋ฐ์ดํฐ ์์ฑ๊ธฐ
class StockDataGenerator {
constructor() {
this.stocks = {
'AAPL': { price: 150, volatility: 2 },
'GOOGL': { price: 2800, volatility: 30 },
'MSFT': { price: 300, volatility: 3 },
'TSLA': { price: 700, volatility: 15 }
};
this.subscribers = new Map();
this.intervals = new Map();
}
subscribe(symbol, callback, clientId) {
if (!this.subscribers.has(symbol)) {
this.subscribers.set(symbol, new Map());
}
this.subscribers.get(symbol).set(clientId, callback);
// ํด๋น ์ฌ๋ณผ์ ๋ฐ์ดํฐ ์์ฑ ์์
if (!this.intervals.has(symbol)) {
this.startGenerating(symbol);
}
}
unsubscribe(symbol, clientId) {
if (this.subscribers.has(symbol)) {
this.subscribers.get(symbol).delete(clientId);
// ๊ตฌ๋
์๊ฐ ์์ผ๋ฉด ์์ฑ ์ค์ง
if (this.subscribers.get(symbol).size === 0) {
this.stopGenerating(symbol);
this.subscribers.delete(symbol);
}
}
}
startGenerating(symbol) {
const interval = setInterval(() => {
const data = this.generateStockData(symbol);
this.broadcast(symbol, data);
}, 1000); // 1์ด๋ง๋ค ๋ฐ์ดํฐ ์์ฑ
this.intervals.set(symbol, interval);
}
stopGenerating(symbol) {
if (this.intervals.has(symbol)) {
clearInterval(this.intervals.get(symbol));
this.intervals.delete(symbol);
}
}
generateStockData(symbol) {
const stock = this.stocks[symbol];
// ๋๋ค ์ํฌ๋ก ๊ฐ๊ฒฉ ๋ณ๋
const change = (Math.random() - 0.5) * stock.volatility;
stock.price += change;
// ๊ฐ๊ฒฉ์ด ๋๋ฌด ๋ฎ์์ง์ง ์๋๋ก
if (stock.price < 10) stock.price = 10;
const changePercent = (change / stock.price) * 100;
return {
symbol: symbol,
price: stock.price,
changePercent: changePercent,
volume: Math.floor(Math.random() * 1000000) + 500000,
high: stock.price + Math.random() * stock.volatility,
low: stock.price - Math.random() * stock.volatility,
timestamp: Date.now()
};
}
broadcast(symbol, data) {
if (this.subscribers.has(symbol)) {
this.subscribers.get(symbol).forEach(callback => {
callback(data);
});
}
}
}
module.exports = StockDataGenerator;
๐ ํ๋ก์ ํธ ์คํ ๋ฐฉ๋ฒ
1. ์์กด์ฑ ์ค์น: npm install express ws
2. ์๋ฒ ์์: node server/server.js
3. ๋ธ๋ผ์ฐ์ ์์ http://localhost:8080 ์ ์
4. ์ค์๊ฐ์ผ๋ก ๋ณํ๋ ์ฃผ์ ์ฐจํธ ํ์ธ! ๐
๐ ์ค๋ฌด์์ ์์ฃผ ์ฐ๋ ๊ณ ๊ธ ํจํด
์ด์ ์ข ๋ ์ค๋ฌด์ ์ธ ์๊ธฐ๋ฅผ ํด๋ณผ๊ฒ์! ์ค์ ํ๋ก๋์ ํ๊ฒฝ์์ ์ฐ์ด๋ ํจํด๋ค์ด์์ ใ ใ
๐ ๋ฐ์ดํฐ ์คํธ๋ฆผ ํ์ดํ๋ผ์ธ
๋๊ท๋ชจ ์ค์๊ฐ ์์คํ ์์๋ ๋ฐ์ดํฐ๊ฐ ์ฌ๋ฌ ๋จ๊ณ๋ฅผ ๊ฑฐ์ณ์ ์ฒ๋ฆฌ๋ผ์. ์ด๊ฑธ ํ์ดํ๋ผ์ธ ํจํด์ผ๋ก ๊ตฌํํ๋ฉด ๊น๋ํด์!
// ๋ฐ์ดํฐ ํ์ดํ๋ผ์ธ ๊ตฌํ
class DataPipeline {
constructor() {
this.stages = [];
}
addStage(stage) {
this.stages.push(stage);
return this;
}
async process(data) {
let result = data;
for (const stage of this.stages) {
try {
result = await stage.execute(result);
} catch (error) {
console.error(`Stage ${stage.name} ์๋ฌ:`, error);
throw error;
}
}
return result;
}
}
// ํ์ดํ๋ผ์ธ ์คํ
์ด์ง๋ค
class ValidationStage {
constructor() {
this.name = 'Validation';
}
async execute(data) {
// ๋ฐ์ดํฐ ๊ฒ์ฆ
if (!data || typeof data !== 'object') {
throw new Error('Invalid data format');
}
if (!data.timestamp || !data.value) {
throw new Error('Missing required fields');
}
return data;
}
}
class TransformationStage {
constructor() {
this.name = 'Transformation';
}
async execute(data) {
// ๋ฐ์ดํฐ ๋ณํ
return {
...data,
value: parseFloat(data.value),
timestamp: new Date(data.timestamp),
processedAt: new Date()
};
}
}
class EnrichmentStage {
constructor() {
this.name = 'Enrichment';
this.cache = new Map();
}
async execute(data) {
// ์ถ๊ฐ ์ ๋ณด ๋ณด๊ฐ
const metadata = await this.fetchMetadata(data.id);
return {
...data,
metadata: metadata
};
}
async fetchMetadata(id) {
// ์บ์ ํ์ธ
if (this.cache.has(id)) {
return this.cache.get(id);
}
// API ํธ์ถ (์๋ฎฌ๋ ์ด์
)
const metadata = {
category: 'sensor',
location: 'Building A',
unit: 'celsius'
};
this.cache.set(id, metadata);
return metadata;
}
}
class AggregationStage {
constructor(windowSize = 5) {
this.name = 'Aggregation';
this.windowSize = windowSize;
this.buffer = [];
}
async execute(data) {
this.buffer.push(data);
if (this.buffer.length > this.windowSize) {
this.buffer.shift();
}
// ์๋์ฐ ๋ด ํต๊ณ ๊ณ์ฐ
const values = this.buffer.map(d => d.value);
const avg = values.reduce((a, b) => a + b, 0) / values.length;
const max = Math.max(...values);
const min = Math.min(...values);
return {
...data,
statistics: {
average: avg,
max: max,
min: min,
count: this.buffer.length
}
};
}
}
// ํ์ดํ๋ผ์ธ ๊ตฌ์ฑ ๋ฐ ์ฌ์ฉ
const pipeline = new DataPipeline()
.addStage(new ValidationStage())
.addStage(new TransformationStage())
.addStage(new EnrichmentStage())
.addStage(new AggregationStage(10));
// WebSocket์ผ๋ก ๋ฐ์ ๋ฐ์ดํฐ ์ฒ๋ฆฌ
socket.onmessage = async function(event) {
try {
const rawData = JSON.parse(event.data);
const processedData = await pipeline.process(rawData);
// ์๊ฐํ ์
๋ฐ์ดํธ
updateVisualization(processedData);
} catch (error) {
console.error('ํ์ดํ๋ผ์ธ ์ฒ๋ฆฌ ์๋ฌ:', error);
}
};
๐ฆ ์ํ ๊ด๋ฆฌ ํจํด
๋ณต์กํ ์ค์๊ฐ ์ฑ์์๋ ์ํ ๊ด๋ฆฌ๊ฐ ์ง์ง ์ค์ํด์! Redux ๊ฐ์ ๊ฑฐ ์ฐ๋ฉด ์ข์๋ฐ, ๊ฐ๋จํ ๋ฒ์ ์ ๋ง๋ค์ด๋ณผ๊ฒ์.
// ์ค์๊ฐ ๋ฐ์ดํฐ์ฉ ์ํ ๊ด๋ฆฌ
class RealtimeStore {
constructor(initialState = {}) {
this.state = initialState;
this.listeners = new Set();
this.history = [];
this.maxHistory = 100;
}
getState() {
return { ...this.state };
}
setState(updates) {
const oldState = this.state;
this.state = {
...this.state,
...updates,
lastUpdated: Date.now()
};
// ํ์คํ ๋ฆฌ ์ ์ฅ
this.history.push({
timestamp: Date.now(),
state: { ...this.state }
});
if (this.history.length > this.maxHistory) {
this.history.shift();
}
// ๋ฆฌ์ค๋๋ค์๊ฒ ์๋ฆผ
this.notifyListeners(oldState, this.state);
}
subscribe(listener) {
this.listeners.add(listener);
// ๊ตฌ๋
ํด์ ํจ์ ๋ฐํ
return () => {
this.listeners.delete(listener);
};
}
notifyListeners(oldState, newState) {
this.listeners.forEach(listener => {
try {
listener(newState, oldState);
} catch (error) {
console.error('๋ฆฌ์ค๋ ์๋ฌ:', error);
}
});
}
getHistory(duration = 60000) {
const cutoff = Date.now() - duration;
return this.history.filter(entry => entry.timestamp > cutoff);
}
// ์๊ณ์ด ๋ฐ์ดํฐ ์ถ๊ฐ
addTimeSeries(key, value) {
const series = this.state[key] || [];
series.push({
timestamp: Date.now(),
value: value
});
// ์ต๋ 100๊ฐ ์ ์ง
if (series.length > 100) {
series.shift();
}
this.setState({ [key]: series });
}
}
// ์ฌ์ฉ ์์
const store = new RealtimeStore({
temperature: [],
humidity: [],
pressure: [],
alerts: []
});
// ์ํ ๋ณํ ๊ตฌ๋
const unsubscribe = store.subscribe((newState, oldState) => {
console.log('์ํ ์
๋ฐ์ดํธ:', newState);
// ์จ๋๊ฐ ์๊ณ๊ฐ ์ด๊ณผ์ ์๋ฆผ
if (newState.temperature.length > 0) {
const latest = newState.temperature[newState.temperature.length - 1];
if (latest.value > 30) {
store.setState({
alerts: [...newState.alerts, {
type: 'warning',
message: '์จ๋๊ฐ ๋์ต๋๋ค!',
timestamp: Date.now()
}]
});
}
}
// ์ฐจํธ ์
๋ฐ์ดํธ
updateCharts(newState);
});
// WebSocket ๋ฐ์ดํฐ ์ฒ๋ฆฌ
socket.onmessage = function(event) {
const data = JSON.parse(event.data);
// ์๊ณ์ด ๋ฐ์ดํฐ ์ถ๊ฐ
store.addTimeSeries('temperature', data.temperature);
store.addTimeSeries('humidity', data.humidity);
store.addTimeSeries('pressure', data.pressure);
};
// ์ฐจํธ ์
๋ฐ์ดํธ ํจ์
function updateCharts(state) {
// ์จ๋ ์ฐจํธ
if (state.temperature) {
temperatureChart.data.labels = state.temperature.map(d =>
new Date(d.timestamp).toLocaleTimeString()
);
temperatureChart.data.datasets[0].data = state.temperature.map(d => d.value);
temperatureChart.update('none');
}
// ์ต๋ ์ฐจํธ
if (state.humidity) {
humidityChart.data.labels = state.humidity.map(d =>
new Date(d.timestamp).toLocaleTimeString()
);
humidityChart.data.datasets[0].data = state.humidity.map(d => d.value);
humidityChart.update('none');
}
}
๐ ์ฌ๋ฅ๋ท์์ ๋ฐฐ์ฐ๊ณ ๊ฐ๋ฅด์น๊ธฐ
์ค์๊ฐ ๋ฐ์ดํฐ ์๊ฐํ ๊ฐ์ ๊ณ ๊ธ ๊ธฐ์ ์ ํผ์ ๋ฐฐ์ฐ๊ธฐ ์ด๋ ค์ธ ์ ์์ด์. ์ฌ๋ฅ๋ท์์๋ ์ด๋ฐ ์ ๋ฌธ ๊ธฐ์ ์ ๊ฐ์ง ๊ฐ๋ฐ์๋ค์ด ์ง์ ๋ฉํ ๋ง์ ํด์ฃผ๊ฑฐ๋ ์! ์ค๋ฌด ๊ฒฝํ์ด ํ๋ถํ ์๋์ด ๊ฐ๋ฐ์์๊ฒ 1:1๋ก ๋ฐฐ์ธ ์ ์์ด์ ์ง์ง ํจ์จ์ ์ด์์ ใ ใ
๋ฐ๋๋ก ์ฌ๋ฌ๋ถ์ด ์ค์๊ฐ ์๊ฐํ ์ ๋ฌธ๊ฐ๋ผ๋ฉด? ์ฌ๋ฅ๋ท์์ ์ฌ๋ฌ๋ถ์ ์ง์์ ๊ณต์ ํ๊ณ ์์ต๋ ์ฐฝ์ถํ ์ ์์ด์! ์์ฆ ์ด๋ฐ ๊ธฐ์ ์์๊ฐ ์์ฒญ ๋ง๊ฑฐ๋ ์ ๐ฐ
๐ก ์ฌ๋ฅ๋ท์์ ์ธ๊ธฐ ์๋ ์ค์๊ฐ ์๊ฐํ ๊ด๋ จ ์ฌ๋ฅ๋ค
โข ์ค์๊ฐ ๋์๋ณด๋ ๊ตฌ์ถ ๋ฉํ ๋ง
โข WebSocket ํ๋ก๊ทธ๋๋ฐ ๊ฐ์
โข D3.js ๊ณ ๊ธ ์๊ฐํ ํํ ๋ฆฌ์ผ
โข ์ค์๊ฐ ๋ชจ๋ํฐ๋ง ์์คํ
๊ตฌ์ถ ์ปจ์คํ
โข ์ฑ๋ฅ ์ต์ ํ ๋
ธํ์ฐ ๊ณต์
๐ฅ ํธ๋ฌ๋ธ์ํ - ์์ฃผ ๋ง๋๋ ๋ฌธ์ ๋ค
์ค์ ์์ ์ง์ง ๋ง์ด ๊ฒช๋ ๋ฌธ์ ๋ค๊ณผ ํด๊ฒฐ๋ฒ์ ์ ๋ฆฌํด๋ดค์ด์!
โ ๋ฌธ์ 1: ๋ฉ๋ชจ๋ฆฌ ๋์
// ๋์ ์ - ๋ฉ๋ชจ๋ฆฌ ๋์ ๋ฐ์
class BadChart {
constructor() {
this.data = [];
setInterval(() => {
this.data.push(Math.random());
this.render(); // ๊ณ์ ์์!
}, 1000);
}
}
// ์ข์ ์ - ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ
class GoodChart {
constructor(maxDataPoints = 50) {
this.data = [];
this.maxDataPoints = maxDataPoints;
this.interval = null;
}
start() {
this.interval = setInterval(() => {
this.data.push(Math.random());
// ์ค๋๋ ๋ฐ์ดํฐ ์ ๊ฑฐ
if (this.data.length > this.maxDataPoints) {
this.data.shift();
}
this.render();
}, 1000);
}
stop() {
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
}
}
destroy() {
this.stop();
this.data = null;
}
}
โ ๋ฌธ์ 2: ์ฐ๊ฒฐ ๋๊น ์ฒ๋ฆฌ
// ๊ฐ๋ ฅํ ์ฌ์ฐ๊ฒฐ ๋ก์ง
class RobustWebSocket {
constructor(url, options = {}) {
this.url = url;
this.options = {
reconnectInterval: 1000,
maxReconnectInterval: 30000,
reconnectDecay: 1.5,
maxReconnectAttempts: null,
...options
};
this.reconnectAttempts = 0;
this.reconnectTimer = null;
this.forcedClose = false;
this.ws = null;
}
connect() {
this.forcedClose = false;
this.ws = new WebSocket(this.url);
this.ws.onopen = (event) => {
console.log('์ฐ๊ฒฐ ์ฑ๊ณต! ๐');
this.reconnectAttempts = 0;
if (this.options.onOpen) {
this.options.onOpen(event);
}
};
this.ws.onmessage = (event) => {
if (this.options.onMessage) {
this.options.onMessage(event);
}
};
this.ws.onerror = (error) => {
console.error('WebSocket ์๋ฌ:', error);
if (this.options.onError) {
this.options.onError(error);
}
};
this.ws.onclose = (event) => {
console.log('์ฐ๊ฒฐ ์ข
๋ฃ๋จ');
if (this.options.onClose) {
this.options.onClose(event);
}
if (!this.forcedClose) {
this.reconnect();
}
};
}
reconnect() {
if (this.options.maxReconnectAttempts &&
this.reconnectAttempts >= this.options.maxReconnectAttempts) {
console.error('์ต๋ ์ฌ์ฐ๊ฒฐ ์๋ ํ์ ์ด๊ณผ');
return;
}
this.reconnectAttempts++;
const timeout = Math.min(
this.options.reconnectInterval *
Math.pow(this.options.reconnectDecay, this.reconnectAttempts - 1),
this.options.maxReconnectInterval
);
console.log(`${timeout}ms ํ ์ฌ์ฐ๊ฒฐ ์๋ (${this.reconnectAttempts}๋ฒ์งธ)`);
this.reconnectTimer = setTimeout(() => {
console.log('์ฌ์ฐ๊ฒฐ ์ค...');
this.connect();
}, timeout);
}
send(data) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(data);
} else {
console.warn('WebSocket์ด ์ฐ๊ฒฐ๋์ง ์์');
}
}
close() {
this.forcedClose = true;
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
}
if (this.ws) {
this.ws.close();
}
}
}
// ์ฌ์ฉ ์์
const robustWs = new RobustWebSocket('ws://localhost:8080', {
reconnectInterval: 1000,
maxReconnectInterval: 30000,
reconnectDecay: 1.5,
onOpen: (event) => {
console.log('์ฐ๊ฒฐ๋จ!');
},
onMessage: (event) => {
const data = JSON.parse(event.data);
updateChart(data);
},
onError: (error) => {
console.error('์๋ฌ:', error);
},
onClose: (event) => {
console.log('์ฐ๊ฒฐ ์ข
๋ฃ');
}
});
robustWs.connect();
โ ๋ฌธ์ 3: ์ฐจํธ ๋ ๋๋ง ์ฑ๋ฅ
// ์ฑ๋ฅ ์ต์ ํ๋ ์ฐจํธ ์
๋ฐ์ดํธ
class OptimizedChart {
constructor(canvas, options = {}) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.data = [];
this.maxPoints = options.maxPoints || 100;
this.updateThrottle = options.updateThrottle || 16; // 60fps
this.lastUpdate = 0;
this.pendingUpdate = false;
this.offscreenCanvas = null;
// ์คํ์คํฌ๋ฆฐ ์บ๋ฒ์ค ์์ฑ (๋๋ธ ๋ฒํผ๋ง)
if (typeof OffscreenCanvas !== 'undefined') {
this.offscreenCanvas = new OffscreenCanvas(
canvas.width,
canvas.height
);
this.offscreenCtx = this.offscreenCanvas.getContext('2d');
}
}
addData(value) {
this.data.push({
value: value,
timestamp: Date.now()
});
if (this.data.length > this.maxPoints) {
this.data.shift();
}
this.scheduleUpdate();
}
scheduleUpdate() {
if (this.pendingUpdate) return;
const now = Date.now();
const timeSinceLastUpdate = now - this.lastUpdate;
if (timeSinceLastUpdate >= this.updateThrottle) {
this.update();
} else {
this.pendingUpdate = true;
setTimeout(() => {
this.pendingUpdate = false;
this.update();
}, this.updateThrottle - timeSinceLastUpdate);
}
}
update() {
this.lastUpdate = Date.now();
// ์คํ์คํฌ๋ฆฐ ์บ๋ฒ์ค์ ๋จผ์ ๊ทธ๋ฆฌ๊ธฐ
const ctx = this.offscreenCtx || this.ctx;
const canvas = this.offscreenCanvas || this.canvas;
// ์บ๋ฒ์ค ํด๋ฆฌ์ด
ctx.clearRect(0, 0, canvas.width, canvas.height);
// ๋ฐฐ๊ฒฝ ๊ทธ๋ฆฌ๋
this.drawGrid(ctx, canvas);
// ๋ฐ์ดํฐ ๋ผ์ธ
this.drawLine(ctx, canvas);
// ์คํ์คํฌ๋ฆฐ์์ ๋ฉ์ธ ์บ๋ฒ์ค๋ก ๋ณต์ฌ
if (this.offscreenCanvas) {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.drawImage(this.offscreenCanvas, 0, 0);
}
}
drawGrid(ctx, canvas) {
ctx.strokeStyle = 'rgba(0, 0, 0, 0.05)';
ctx.lineWidth = 1;
// ์ํ์
for (let i = 0; i <= 10; i++) {
const y = (canvas.height / 10) * i;
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
ctx.stroke();
}
// ์์ง์
for (let i = 0; i <= 10; i++) {
const x = (canvas.width / 10) * i;
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.stroke();
}
}
drawLine(ctx, canvas) {
if (this.data.length < 2) return;
const width = canvas.width;
const height = canvas.height;
const step = width / this.maxPoints;
// ์ต์/์ต๋๊ฐ ์ฐพ๊ธฐ
const values = this.data.map(d => d.value);
const min = Math.min(...values);
const max = Math.max(...values);
const range = max - min || 1;
// ๋ผ์ธ ๊ทธ๋ฆฌ๊ธฐ
ctx.beginPath();
ctx.strokeStyle = '#667eea';
ctx.lineWidth = 2;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
this.data.forEach((point, index) => {
const x = index * step;
const y = height - ((point.value - min) / range) * height;
if (index === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
});
ctx.stroke();
// ์์ญ ์ฑ์ฐ๊ธฐ
ctx.lineTo(width, height);
ctx.lineTo(0, height);
ctx.closePath();
ctx.fillStyle = 'rgba(102, 126, 234, 0.1)';
ctx.fill();
}
}
๐ ๋ฏธ๋ ํธ๋ ๋์ ๋ฐ์ ๋ฐฉํฅ
์ค์๊ฐ ๋ฐ์ดํฐ ์๊ฐํ ๊ธฐ์ ์ ๊ณ์ ์งํํ๊ณ ์์ด์! ์์ผ๋ก ์ฃผ๋ชฉํด์ผ ํ ํธ๋ ๋๋ค์ ์ดํด๋ณผ๊น์?
๐ค AI/ML ํตํฉ
๋จธ์ ๋ฌ๋์ ํ์ฉํ ์ด์ ํ์ง์ ์์ธก ์๊ฐํ๊ฐ ๋์ธ๊ฐ ๋๊ณ ์์ด์. ์ค์๊ฐ์ผ๋ก ๋ค์ด์ค๋ ๋ฐ์ดํฐ๋ฅผ AI๊ฐ ๋ถ์ํด์ ๋ฏธ๋๋ฅผ ์์ธกํ๊ณ , ๊ทธ๊ฑธ ์๊ฐํํ๋ ๊ฑฐ์ฃ !
// TensorFlow.js๋ฅผ ํ์ฉํ ์ค์๊ฐ ์์ธก
import * as tf from '@tensorflow/tfjs';
class PredictiveChart {
constructor() {
this.model = null;
this.data = [];
this.predictions = [];
this.sequenceLength = 10;
}
async loadModel() {
// ์ฌ์ ํ์ต๋ ๋ชจ๋ธ ๋ก๋
this.model = await tf.loadLayersModel('/models/timeseries/model.json');
console.log('๋ชจ๋ธ ๋ก๋ ์๋ฃ!');
}
async addDataAndPredict(value) {
this.data.push(value);
if (this.data.length > 100) {
this.data.shift();
}
// ์ถฉ๋ถํ ๋ฐ์ดํฐ๊ฐ ์์ด๋ฉด ์์ธก
if (this.data.length >= this.sequenceLength) {
const prediction = await this.predict();
this.predictions.push(prediction);
if (this.predictions.length > 20) {
this.predictions.shift();
}
}
}
async predict() {
// ์ต๊ทผ ๋ฐ์ดํฐ๋ก ์ํ์ค ์์ฑ
const sequence = this.data.slice(-this.sequenceLength);
// ์ ๊ทํ
const mean = sequence.reduce((a, b) => a + b) / sequence.length;
const std = Math.sqrt(
sequence.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / sequence.length
);
const normalized = sequence.map(val => (val - mean) / (std || 1));
// ํ
์๋ก ๋ณํ
const input = tf.tensor3d([normalized], [1, this.sequenceLength, 1]);
// ์์ธก
const output = this.model.predict(input);
const prediction = await output.data();
// ์ญ์ ๊ทํ
const denormalized = prediction[0] * (std || 1) + mean;
// ๋ฉ๋ชจ๋ฆฌ ์ ๋ฆฌ
input.dispose();
output.dispose();
return denormalized;
}
getChartData() {
return {
actual: this.data,
predicted: this.predictions
};
}
}
๐ WebAssembly ํ์ฉ
๋์ฉ๋ ๋ฐ์ดํฐ ์ฒ๋ฆฌ์๋ WebAssembly๊ฐ ๋ต์ด์์! JavaScript๋ณด๋ค ํจ์ฌ ๋น ๋ฅด๊ฑฐ๋ ์ ใ ใ
// Rust๋ก ์์ฑํ ๋ฐ์ดํฐ ์ฒ๋ฆฌ ๋ก์ง์ WASM์ผ๋ก ์ปดํ์ผ
// rust_processor.rs
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub struct DataProcessor {
buffer: Vec<f64>,
window_size: usize,
}
#[wasm_bindgen]
impl DataProcessor {
#[wasm_bindgen(constructor)]
pub fn new(window_size: usize) -> DataProcessor {
DataProcessor {
buffer: Vec::new(),
window_size,
}
}
pub fn add_value(&mut self, value: f64) {
self.buffer.push(value);
if self.buffer.len() > self.window_size {
self.buffer.remove(0);
}
}
pub fn calculate_statistics(&self) -> JsValue {
if self.buffer.is_empty() {
return JsValue::NULL;
}
let sum: f64 = self.buffer.iter().sum();
let mean = sum / self.buffer.len() as f64;
let variance: f64 = self.buffer
.iter()
.map(|x| (x - mean).powi(2))
.sum::<f64>() / self.buffer.len() as f64;
let std_dev = variance.sqrt();
let max = self.buffer.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
let min = self.buffer.iter().cloned().fold(f64::INFINITY, f64::min);
// JavaScript ๊ฐ์ฒด๋ก ๋ฐํ
let result = js_sys::Object::new();
js_sys::Reflect::set(&result, &"mean".into(), &mean.into()).unwrap();
js_sys::Reflect::set(&result, &"stdDev".into(), &std_dev.into()).unwrap();
js_sys::Reflect::set(&result, &"max".into(), &max.into()).unwrap();
js_sys::Reflect::set(&result, &"min".into(), &min.into()).unwrap();
result.into()
}
}
// JavaScript์์ WASM ๋ชจ๋ ์ฌ์ฉ
import init, { DataProcessor } from './rust_processor.js';
async function setupWasmProcessor() {
// WASM ์ด๊ธฐํ
await init();
const processor = new DataProcessor(100);
// WebSocket์ผ๋ก ๋ฐ์ดํฐ ์์
socket.onmessage = function(event) {
const data = JSON.parse(event.data);
// WASM์ผ๋ก ๊ณ ์ ์ฒ๋ฆฌ
processor.add_value(data.value);
const stats = processor.calculate_statistics();
console.log('ํต๊ณ:', stats);
updateChart(stats);
};
}
setupWasmProcessor();
๐ฎ 3D ์๊ฐํ
Three.js๋ฅผ ํ์ฉํ 3D ์ค์๊ฐ ์๊ฐํ๋ ์ ์ ์ธ๊ธฐ๋ฅผ ์ป๊ณ ์์ด์! ํนํ IoT ์ผ์ ๋ฐ์ดํฐ๋ ๋คํธ์ํฌ ํ ํด๋ก์ง ๊ฐ์ ๊ฑธ ํํํ ๋ ์ ์ฉํด์.
// Three.js๋ก 3D ์ค์๊ฐ ์๊ฐํ
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
class Realtime3DChart {
constructor(container) {
this.container = container;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(
75,
container.clientWidth / container.clientHeight,
0.1,
1000
);
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.renderer.setSize(container.clientWidth, container.clientHeight);
this.renderer.setClearColor(0xf0f0f0);
container.appendChild(this.renderer.domElement);
this.controls = new OrbitControls(this.camera, this.renderer.domElement);
this.camera.position.set(0, 5, 10);
this.controls.update();
this.dataPoints = [];
this.maxPoints = 50;
this.setupLights();
this.setupGrid();
this.animate();
}
setupLights() {
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
this.scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(10, 10, 5);
this.scene.add(directionalLight);
}
setupGrid() {
const gridHelper = new THREE.GridHelper(20, 20, 0xcccccc, 0xeeeeee);
this.scene.add(gridHelper);
}
addData(value) {
// ์๋ก์ด ๋ฐ์ดํฐ ํฌ์ธํธ ์์ฑ
const geometry = new THREE.SphereGeometry(0.2, 16, 16);
const material = new THREE.MeshPhongMaterial({
color: this.getColorForValue(value),
emissive: 0x072534,
shininess: 30
});
const sphere = new THREE.Mesh(geometry, material);
// ์์น ์ค์
const x = (this.dataPoints.length * 0.4) - 10;
const y = value / 10; // ๊ฐ์ ๋ฐ๋ผ ๋์ด ์กฐ์
const z = 0;
sphere.position.set(x, y, z);
this.scene.add(sphere);
this.dataPoints.push({
mesh: sphere,
value: value,
timestamp: Date.now()
});
// ์ค๋๋ ํฌ์ธํธ ์ ๊ฑฐ
if (this.dataPoints.length > this.maxPoints) {
const old = this.dataPoints.shift();
this.scene.remove(old.mesh);
old.mesh.geometry.dispose();
old.mesh.material.dispose();
}
// ๋ผ์ธ์ผ๋ก ์ฐ๊ฒฐ
this.updateConnections();
}
updateConnections() {
// ๊ธฐ์กด ๋ผ์ธ ์ ๊ฑฐ
const lines = this.scene.children.filter(child => child.type === 'Line');
lines.forEach(line => {
this.scene.remove(line);
line.geometry.dispose();
line.material.dispose();
});
// ์ ๋ผ์ธ ์์ฑ
if (this.dataPoints.length < 2) return;
const points = this.dataPoints.map(dp => dp.mesh.position);
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color: 0x667eea,
linewidth: 2
});
const line = new THREE.Line(geometry, material);
this.scene.add(line);
}
getColorForValue(value) {
// ๊ฐ์ ๋ฐ๋ผ ์์ ๋ณ๊ฒฝ
if (value > 80) return 0xff4444; // ๋นจ๊ฐ
if (value > 60) return 0xffaa44; // ์ฃผํฉ
if (value > 40) return 0xffff44; // ๋
ธ๋
return 0x44ff44; // ์ด๋ก
}
animate() {
requestAnimationFrame(() => this.animate());
this.controls.update();
this.renderer.render(this.scene, this.camera);
}
handleResize() {
const width = this.container.clientWidth;
const height = this.container.clientHeight;
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
this.renderer.setSize(width, height);
}
}
// ์ฌ์ฉ ์์
const chart3D = new Realtime3DChart(document.getElementById('chart-container'));
socket.onmessage = function(event) {
const data = JSON.parse(event.data);
chart3D.addData(data.value);
};
window.addEventListener('resize', () => chart3D.handleResize());
๐ ๋ง๋ฌด๋ฆฌํ๋ฉฐ
์... ์ฌ๊ธฐ๊น์ง ์ฝ์ผ์ จ๋ค๋ฉด ์ง์ง ๋๋จํ์ธ์! ๐ ์ค์๊ฐ ๋ฐ์ดํฐ ์๊ฐํ๋ ์ฒ์์ ์ด๋ ค์ ๋ณด์ด์ง๋ง, ํ๋์ฉ ์ฐจ๊ทผ์ฐจ๊ทผ ๋ฐฐ์ฐ๋ค ๋ณด๋ฉด ์ ๋ง ์ฌ๋ฏธ์๋ ๋ถ์ผ์์.
ํต์ฌ์ ์ ๋ฆฌํ์๋ฉด:
๐ฏ ์ค์๊ฐ ์๊ฐํ ํต์ฌ ์์ฝ
1๏ธโฃ ํต์ ๋ฐฉ์ ์ ํ - WebSocket, SSE, Polling ์ค ์ํฉ์ ๋ง๊ฒ
2๏ธโฃ ์๊ฐํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ - Chart.js(๊ฐ๋จ), D3.js(์์ ๋), ECharts(์ฑ๋ฅ)
3๏ธโฃ ์ฑ๋ฅ ์ต์ ํ - ์ํ๋ง, RAF, Web Workers ํ์ฉ
4๏ธโฃ ๋ณด์ - WSS, ์ธ์ฆ, Rate Limiting ํ์
5๏ธโฃ ์์ ์ฑ - ์ฌ์ฐ๊ฒฐ ๋ก์ง, ์๋ฌ ํธ๋ค๋ง, ๋ชจ๋ํฐ๋ง
์ค๋ฌด์์๋ ์ด๋ฐ ๊ธฐ์ ๋ค์ ์กฐํฉํด์ ์ฌ์ฉํ๊ฒ ๋ผ์. ์ฒ์์ ๊ฐ๋จํ ํ๋ก์ ํธ๋ถํฐ ์์ํด์ ์ ์ ๋ณต์กํ ๊ฑธ ๋ง๋ค์ด๋ณด์ธ์! ๊ทธ๋ฆฌ๊ณ ๋งํ๋ ๋ถ๋ถ์ด ์์ผ๋ฉด ์ฌ๋ฅ๋ท์์ ์ ๋ฌธ๊ฐ์ ๋์์ ๋ฐ๋ ๊ฒ๋ ์ข์ ๋ฐฉ๋ฒ์ด์์ ใ ใ
์ค์๊ฐ ๋ฐ์ดํฐ ์๊ฐํ๋ ์์ผ๋ก๋ ๊ณ์ ๋ฐ์ ํ ๋ถ์ผ์์. AI, WebAssembly, 3D ์๊ฐํ ๋ฑ ์๋ก์ด ๊ธฐ์ ๋ค์ด ๊ณ์ ๋์ค๊ณ ์์ผ๋๊น์. ์ง๊ธ ๋ฐฐ์๋๋ฉด ๋์ค์ ์ ๋ง ์ ์ฉํ๊ฒ ์ธ ์ ์์ ๊ฑฐ์์!
์ฌ๋ฌ๋ถ์ ํ๋ก์ ํธ์ ๋ฉ์ง ์ค์๊ฐ ์๊ฐํ๋ฅผ ์ถ๊ฐํด๋ณด์ธ์. ์ฌ์ฉ์๋ค์ด ์~ ํ๊ณ ๊ฐํํ ๊ฑฐ์์! ๐โจ
๐ช ํ์ดํ
! ์ฌ๋ฌ๋ถ๋ ์ถฉ๋ถํ ํ ์ ์์ด์!
๐จ ๋ฐ์ดํฐ๋ฅผ ์๋ฆ๋ต๊ฒ ํํํ๋ ๊ฐ๋ฐ์๊ฐ ๋์ธ์!
๊ด๋ จ ํค์๋
๋๊ธ ์์ฑ
์ด ๊ธ์ ๋ํ ์ฌ๋ฌ๋ถ์ ์๊ฐ์ ๋ค๋ ค์ฃผ์ธ์
๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค
๋๊ธ์ ์์ฑํ๋ ค๋ฉด ๋จผ์ ๋ก๊ทธ์ธํด์ฃผ์ธ์.
๋๊ธ 0
์ง์์ธ์ ์ฒ - ์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
- ์ ์๊ถ ๋ฐ ์์ ๊ถ: ๋ณธ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ๋ ์ AI ๊ธฐ์ ๋ก ์์ฑ๋์์ผ๋ฉฐ, ๋ํ๋ฏผ๊ตญ ์ ์๊ถ๋ฒ ๋ฐ ๊ตญ์ ์ ์๊ถ ํ์ฝ์ ์ํด ๋ณดํธ๋ฉ๋๋ค.
- AI ์์ฑ ์ปจํ ์ธ ์ ๋ฒ์ ์ง์: ๋ณธ AI ์์ฑ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ์ง์ ์ฐฝ์๋ฌผ๋ก ์ธ์ ๋๋ฉฐ, ๊ด๋ จ ๋ฒ๊ท์ ๋ฐ๋ผ ์ ์๊ถ ๋ณดํธ๋ฅผ ๋ฐ์ต๋๋ค.
- ์ฌ์ฉ ์ ํ: ์ฌ๋ฅ๋ท์ ๋ช ์์ ์๋ฉด ๋์ ์์ด ๋ณธ ์ปจํ ์ธ ๋ฅผ ๋ณต์ , ์์ , ๋ฐฐํฌ, ๋๋ ์์ ์ ์ผ๋ก ํ์ฉํ๋ ํ์๋ ์๊ฒฉํ ๊ธ์ง๋ฉ๋๋ค.
- ๋ฐ์ดํฐ ์์ง ๊ธ์ง: ๋ณธ ์ปจํ ์ธ ์ ๋ํ ๋ฌด๋จ ์คํฌ๋ํ, ํฌ๋กค๋ง, ๋ฐ ์๋ํ๋ ๋ฐ์ดํฐ ์์ง์ ๋ฒ์ ์ ์ฌ์ ๋์์ด ๋ฉ๋๋ค.
- AI ํ์ต ์ ํ: ์ฌ๋ฅ๋ท์ AI ์์ฑ ์ปจํ ์ธ ๋ฅผ ํ AI ๋ชจ๋ธ ํ์ต์ ๋ฌด๋จ ์ฌ์ฉํ๋ ํ์๋ ๊ธ์ง๋๋ฉฐ, ์ด๋ ์ง์ ์ฌ์ฐ๊ถ ์นจํด๋ก ๊ฐ์ฃผ๋ฉ๋๋ค.
์์ง ๋๊ธ์ด ์์ต๋๋ค.