iosignal 2.2.1 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +248 -114
  2. package/dist/io.d.ts +481 -0
  3. package/dist/io.js +4 -5
  4. package/dist/io.js.map +1 -1
  5. package/dist/io.min.js +4 -5
  6. package/dist/io.min.js.map +1 -1
  7. package/dist/iosignal.js +9559 -0
  8. package/dist/types/client/IOCore.d.ts +408 -0
  9. package/dist/types/client/browser/IOWebSocket.d.ts +75 -0
  10. package/dist/types/common/constants.d.ts +169 -0
  11. package/dist/types/common/payload.d.ts +6 -0
  12. package/dist/types/common/quotaTable.d.ts +47 -0
  13. package/docs/README.ko.md +371 -0
  14. package/docs/iosignal_architecture.png +0 -0
  15. package/examples/react-chat-js/dist/assets/index-Cy4qaVcJ.js +56 -0
  16. package/examples/react-chat-js/dist/assets/index-NETrjYhz.css +1 -0
  17. package/examples/react-chat-js/dist/index.html +14 -0
  18. package/examples/react-chat-js/index.html +13 -0
  19. package/examples/react-chat-js/package-lock.json +1628 -0
  20. package/examples/react-chat-js/package.json +20 -0
  21. package/examples/react-chat-js/src/App.css +61 -0
  22. package/examples/react-chat-js/src/App.jsx +125 -0
  23. package/examples/react-chat-js/src/index.css +13 -0
  24. package/examples/react-chat-js/src/main.jsx +13 -0
  25. package/examples/react-chat-js/src/shared_io.js +12 -0
  26. package/examples/react-chat-js/vite.config.js +7 -0
  27. package/examples/server/index.js +12 -0
  28. package/examples/server/package.json +12 -0
  29. package/package.json +24 -12
  30. package/rollup.config.js +13 -8
  31. package/src/auth/Auth_File.js +1 -1
  32. package/src/client/IOCongSocket.js +20 -9
  33. package/src/client/IOCore.js +422 -77
  34. package/src/client/IOWS.js +12 -15
  35. package/src/client/browser/IOWebSocket.js +217 -0
  36. package/src/common/constants.js +91 -1
  37. package/test-nodejs/server-Auth_File.js +1 -1
  38. package/tsconfig.json +24 -0
  39. package/dist/iosignal.cjs +0 -23
  40. package/dist/iosignal.mjs +0 -23
  41. package/img/iosignal_stack.png +0 -0
  42. package/src/client/IOWebSocket.js +0 -118
  43. package/test-nodejs/client.cjs +0 -17
  44. package/test-nodejs/server-commonjs.cjs +0 -9
  45. /package/{auth_file.mjs → auth_file.js} +0 -0
  46. /package/test-nodejs/{client.mjs → client.js} +0 -0
  47. /package/test-nodejs/{client_api_reply.mjs → client_api_reply.js} +0 -0
  48. /package/test-nodejs/{server-esm.mjs → server.js} +0 -0
  49. /package/test-nodejs/{simple-server.mjs → simple-server.js} +0 -0
@@ -0,0 +1,371 @@
1
+ [ [English](../README.md) | 한국어 ]
2
+
3
+
4
+ # IOSignal
5
+
6
+ IOSignal은 웹 브라우저, Node.js, 아두이노 간의 실시간 통신을 지원합니다. 또한 안전한 인증 및 암호화된 통신을 제공합니다. 시그널링 프로토콜이 내장되어 있어 프로그래밍 없이 서버를 사용할 수 있습니다.
7
+
8
+ ## 설치
9
+
10
+ ```shell
11
+ $ npm i iosignal
12
+ ```
13
+
14
+ ## IOSignal 클라이언트
15
+
16
+ ### React 클라이언트 예제
17
+
18
+ `examples/react-chat-js`에서 샘플 React 프로젝트를 확인할 수 있습니다. 이 예제는 실시간 채팅 기능을 위해 `iosignal`을 React 애플리케이션에 통합하는 방법을 보여줍니다.
19
+
20
+ **주요 개념:**
21
+
22
+ - **`useRef`**: 컴포넌트가 리렌더링되어도 `io` 인스턴스에 대한 안정적인 참조를 유지합니다.
23
+ - **`useEffect`**: `io` 인스턴스의 생명주기를 관리하며, 초기화 및 정리 작업을 포함합니다. 이벤트 핸들러는 이 훅 내에서 설정됩니다.
24
+
25
+ **예제 실행 방법:**
26
+
27
+ 1. 서버 디렉토리로 이동하여 서버를 시작합니다:
28
+ ```shell
29
+ cd examples/server
30
+ npm install
31
+ node .
32
+ ```
33
+ 2. 새 터미널에서 React 프로젝트 디렉토리로 이동하여 종속성을 설치하고 개발 서버를 시작합니다:
34
+ ```shell
35
+ cd examples/react-chat-js
36
+ npm install
37
+ npm run dev
38
+ ```
39
+
40
+ **예제 코드 (`App.jsx`):**
41
+
42
+ 여러 브라우저를 열고 메시지를 입력하면 서버를 통해 서로에게 전달됩니다.
43
+
44
+ ```javascript
45
+ import { useState, useEffect, useRef } from 'react';
46
+ import './App.css';
47
+ import IO from 'iosignal/io.js';
48
+
49
+ const url = 'ws://localhost:7777';
50
+ const channel_tag = 'channel#topic';
51
+
52
+ function App() {
53
+ const [messages, setMessages] = useState([]);
54
+ const [input, setInput] = useState('Hello, World!');
55
+ const [ioState, setIoState] = useState(null);
56
+ const [cid, setCid] = useState(null);
57
+ const [counts, setCounts] = useState({ instances: 0, websockets: 0 });
58
+ const ioRef = useRef(null);
59
+ const messagesEndRef = useRef(null);
60
+
61
+ const scrollToBottom = () => {
62
+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
63
+ };
64
+
65
+ useEffect(() => {
66
+ scrollToBottom();
67
+ }, [messages]);
68
+
69
+ useEffect(() => {
70
+ ioRef.current = new IO(url);
71
+ setCounts({ instances: IO.instanceCount, websockets: IO.webSocketCount });
72
+
73
+ const handleReady = () => {
74
+ console.log('ready cid:', ioRef.current.cid);
75
+ setCid(ioRef.current.cid);
76
+ ioRef.current.subscribe(channel_tag);
77
+ };
78
+
79
+ const handleChange = (state) => {
80
+ setIoState(state);
81
+ setCounts({ instances: IO.instanceCount, websockets: IO.webSocketCount });
82
+ };
83
+
84
+ const handleChannelMessage = (msgObj, tag) => {
85
+ console.log('Received message in App:', msgObj, tag);
86
+ if (typeof msgObj === 'string') {
87
+ msgObj = { text: msgObj, cid: 'cli unknown' };
88
+ }
89
+ setMessages((prevMessages) => [...prevMessages, `${msgObj.cid} : ${msgObj.text}`]);
90
+ };
91
+
92
+ const handleError = (error) => {
93
+ console.error('IO Error in App:', error);
94
+ setIoState(`Error: ${error.message}`);
95
+ };
96
+
97
+ ioRef.current.on('ready', handleReady);
98
+ ioRef.current.on('change', handleChange);
99
+ ioRef.current.on(channel_tag, handleChannelMessage);
100
+ ioRef.current.on('error', handleError);
101
+
102
+ return () => {
103
+ ioRef.current.destroy();
104
+ console.log('IO instance destroyed.');
105
+ ioRef.current = null;
106
+ };
107
+ }, []);
108
+
109
+ const sendMessage = () => {
110
+ if (input.trim()) {
111
+ const msgObj = { text: input, cid: ioRef.current.cid };
112
+ ioRef.current.signal(channel_tag, msgObj);
113
+ setInput('date' + Date.now());
114
+ }
115
+ };
116
+
117
+ const ioStateStyle = {
118
+ color: ioState === 'ready' ? 'green' : 'red',
119
+ fontWeight: 'bold',
120
+ };
121
+
122
+ return (
123
+ <div className="App">
124
+ <h1>React Chat Example</h1>
125
+ <div>URL: {url}</div>
126
+ <div>Channel: {channel_tag}</div>
127
+ <div>IO State: <span style={ioStateStyle}>{ioState}</span></div>
128
+ <div>Client ID: {cid}</div>
129
+ <div>IO Instances: {counts.instances}</div>
130
+ <div>WebSockets Created: {counts.websockets}</div>
131
+ <div className="messages">
132
+ {messages.map((msg, index) => (
133
+ <div key={index}>{msg}</div>
134
+ ))}
135
+ <div ref={messagesEndRef} />
136
+ </div>
137
+ <div className="input-area">
138
+ <input
139
+ type="text"
140
+ value={input}
141
+ onChange={(e) => setInput(e.target.value)}
142
+ onKeyUp={(e) => e.key === 'Enter' && sendMessage()}
143
+ disabled={ioState !== 'ready'}
144
+ />
145
+ <button onClick={sendMessage} disabled={ioState !== 'ready'}>
146
+ Send
147
+ </button>
148
+ </div>
149
+ </div>
150
+ );
151
+ }
152
+
153
+ export default App;
154
+ ```
155
+
156
+ ### 브라우저 클라이언트 : ESM
157
+
158
+ - 로컬 파일: "dist/io.js"
159
+ - CDN: https://cdn.jsdelivr.net/npm/iosignal/dist/io.js
160
+
161
+ ```html
162
+ <html>
163
+
164
+ <script type="module">
165
+ import IO from "../dist/io.js"
166
+
167
+ const io = new IO('wss://io.iosignal.net/ws')
168
+ io.listen('channel#topic', (...args)=>{
169
+ console.log( args )
170
+ })
171
+
172
+ io.on('ready',()=>{
173
+ console.log('ready cid:', io.cid )
174
+ })
175
+
176
+ </script>
177
+
178
+ </html>
179
+ ```
180
+
181
+ ### 브라우저 클라이언트 : UMD(IIFE)
182
+ - 로컬 파일: "dist/io.min.js"
183
+ - CDN: https://cdn.jsdelivr.net/npm/iosignal/dist/io.min.js
184
+
185
+ ```html
186
+ <html>
187
+ <script src="../dist/io.min.js"></script>
188
+ <script>
189
+ console.log('IO', IO) // 기본 전역 변수 이름은 IO
190
+
191
+ var io1 = new IO('ws://localhost:7777')
192
+ var io2 = new IO('ws://localhost:7777')
193
+ var io3 = new IO('ws://localhost:7777')
194
+
195
+ io1.on('error', errorHandler )
196
+ io2.on('error', errorHandler )
197
+ io3.on('error', errorHandler )
198
+
199
+ let channelName = 'io'
200
+
201
+ // 고전적인 스타일의 구독
202
+ io1.on('ready',e=>{
203
+ io1.subscribe(channelName)
204
+ io1.on(channelName, (...args)=>{
205
+ // console.log('io1 received', args )
206
+ let msg = '[io1] ' + JSON.stringify( args )
207
+ addMessage(msg)
208
+ })
209
+ })
210
+
211
+ // iosignal 스타일의 구독
212
+ io2.listen(channelName, (...args)=>{
213
+ // console.log('io2 receive', args )
214
+ let msg = '[io2] ' + JSON.stringify( args )
215
+ addMessage(msg)
216
+ })
217
+
218
+ setInterval(e=>{
219
+ io3.signal(channelName, 'single string') // 단일 문자열 페이로드
220
+ io3.signal(channelName, Date.now(), 'a', 2 , {key: 3} ) // 다중 페이로드
221
+ io3.signal(channelName ) // 페이로드 없는 순수 시그널
222
+ },3000)
223
+
224
+ function addMessage(msg){
225
+ // ...
226
+ }
227
+
228
+ function errorHandler(e){
229
+ // ...
230
+ }
231
+ </script>
232
+
233
+ </html>
234
+ ```
235
+
236
+ ### NodeJS 클라이언트
237
+ ```js
238
+ import { IO } from "iosignal"
239
+
240
+ const io = new IO('wss://io.iosignal.net/ws')
241
+
242
+ io.on('ready', ()=>{
243
+ console.log('ready cid:', io.cid)
244
+ io.signal('#screen','playToggle')
245
+ });
246
+
247
+ io.listen('#notify', (...args)=>{
248
+ console.log( args )
249
+ })
250
+
251
+ io.on('error',err=>{
252
+ console.log('err', err)
253
+ })
254
+
255
+ ```
256
+
257
+ ## IOSignal 서버
258
+
259
+ ```js
260
+ import { Server } from "iosignal"
261
+
262
+ const server = new Server(
263
+ {
264
+ port: 7777,
265
+ congPort: 8888,
266
+ showMetric: 2,
267
+ showMessage: 'message' // 시그널 메시지 표시
268
+ })
269
+
270
+ ```
271
+
272
+ - port: <Number> WebSocket을 통한 IOSignal
273
+ - congPort: <Number> CongSocket을 통한 IOSignal
274
+ - showMetric: 1|2|3 클라이언트 CID(상태) 정보 표시
275
+ - showMessage: "none"|"message" 시그널 버퍼 메시지 표시
276
+ - timeout <milliseconds> 핑 주기 및 타임아웃 (최소 1000)
277
+
278
+ ### IOSignal API
279
+
280
+ IOSignal API 예시
281
+ - src/api_reply.js // 'echo', 'date', 'unixtime'
282
+ - src/api_sudo.js // 서버 관리자 모니터링 명령어
283
+ - src/RedisAPI.js // Redis 명령어 및 응답 서비스
284
+
285
+
286
+ 서버에 API 서비스를 등록하려면 api() 메서드를 사용합니다.
287
+
288
+ `api('api_name', module )`
289
+
290
+ ```js
291
+ // node.js
292
+ import { Server ,api_reply } from 'iosignal'
293
+ const server = new Server( { port: 7777 } )
294
+ server.api('reply', api_reply) // API 모듈 연결
295
+ ```
296
+
297
+ 클라이언트가 reply API를 호출하는 예시
298
+
299
+ ```js
300
+ // 웹 브라우저 API 클라이언트 예시
301
+ <script src="../dist/io.min.js"></script>
302
+ <script>
303
+ const io = new IO('ws://localhost:7777')
304
+
305
+ io.on('ready', async ()=>{
306
+ let res_echo = await io.req('reply', 'echo', 'hello' )
307
+ let res_date = await io.req('reply', 'date' )
308
+ let res_unixtime = await io.req('reply', 'unixtime' )
309
+
310
+ if( res_echo.ok ) console.log( res_echo.body )
311
+ if( res_date.ok ) console.log( res_date.body )
312
+ if( res_unixtime.ok ) console.log( res_unixtime.body )
313
+ });
314
+ </script>
315
+
316
+ // 결과
317
+ [ 'hello' ]
318
+ Fri, 09 Feb 2024 14:24:37 GMT
319
+ 1707488677
320
+
321
+ ```
322
+
323
+ ## 기능
324
+
325
+ ### 내장 메시지 전송 프로토콜
326
+ - 채널 이름을 통한 pub/sub 멀티캐스트.
327
+ - 유니캐스트: CID를 통한 일대일 메시징.
328
+ - `CID`는 통신 ID입니다.
329
+ - CID 구독: CID를 사용하여 하나의 피어 구독.
330
+ - HomeChannel: IP 주소별 그룹화.
331
+
332
+ ### 내장 보안
333
+ - 인증
334
+ - 암호화
335
+ - E2EE
336
+ - `Boho` 덕분입니다 [ [github](https://github.com/remocons/boho) ]
337
+
338
+ ## 연결
339
+ - 웹 브라우저는 WebSocket을 사용합니다.
340
+ - Node.js는 WebSocket 또는 CongSocket을 사용합니다.
341
+ - 아두이노는 CongSocket을 사용합니다.
342
+
343
+ ## IOSignal 서버 아키텍처
344
+ ![IOSignal](../iosignal_architecture.png)
345
+
346
+ ## IOSignal 저장소
347
+
348
+ - Javascript: `iosignal` [ [github](https://github.com/remocons/iosignal) | [npm](https://www.npmjs.com/package/iosignal) ]
349
+ - Node.js 서버 (WebSocket, CongSocket)
350
+ - Node.js 클라이언트 (WebSocket, CongSocket)
351
+ - 웹 브라우저 클라이언트 (WebSocket)
352
+
353
+ - CLI 프로그램
354
+ - `iosignal-cli` [ [github](https://github.com/remocons/iosignal-cli) | [npm](https://www.npmjs.com/package/iosignal-cli) ]
355
+ - 설치: `npm i -g iosignal-cli` 또는 `sudo npm i -g iosignal-cli`
356
+ - Mac, Linux, Windows 지원.
357
+ - 서버 및 클라이언트
358
+
359
+ - 아두이노 iosignal 라이브러리 및 예시:
360
+ - 아두이노 라이브러리 관리자 사용: `iosignal`
361
+ - 또는 `iosignal-arduino` [ [github](https://github.com/remocons/iosignal-arduino) ]
362
+ - 웹 앱 : http://test.iosignal.net
363
+
364
+ - 아두이노 remocon 라이브러리 및 예시:
365
+ - 아두이노 라이브러리 관리자 사용: `remocon`
366
+ - 또는 `remocon-arduino` [ [github](https://github.com/remocons/remocon-arduino) ]
367
+ - 웹 앱 : https://remocon.kr
368
+
369
+ ## 라이선스
370
+
371
+ 이 코드는 MIT 라이선스에 따라 배포됩니다.
Binary file