SocketCluster. 가장 과소평가된 프레임워크. 파트 2: 간단한 예
마르테NNNN / sc-저평가-프레임워크-part2
내가 dev.to에 쓴 기사의 코드를 나타내는 저장소
파트 2: 간단한 예
요약
에서 우리는 SocketCluster가 무엇인지, 어떤 프로젝트/회사에서 그것을 사용하는지 소개했습니다.
SocketCluster 프로젝트 설정.
NOTE
In this article I will focus solely on SocketCluster and not implement Vue yet. We will do some vanilla client js in the index.html
file served by SocketCluster.
프로젝트를 스캐폴드하려면 socketcluster-cli
가 필요합니다. npm i -g socketcluster
를 실행하여 설치합니다. socketcluster create <project-name>
를 사용하여 프로젝트를 시작할 수 있습니다. 코드 편집기를 열고 무엇이 있는지 살펴보겠습니다. 프로젝트는 두 개의 디렉토리kubernetes
및 public
와 일부 파일로 구성됩니다. kubernetes
는 kubernetes
서비스로 배포할 모든 구성 파일이 있는 곳입니다. 이에 대해서는 추후 기사에서 다루도록 하겠습니다. public
는 Express에서 제공하는 디렉토리이며 SocketCluster를 실행하면 localhost:8000을 탐색하여 액세스할 수 있습니다. SocketCluster를 실행하고 npm run start
를 실행하여 무엇을 할 수 있는지 살펴보겠습니다. 기본 포트는 8000
입니다.
마법이 일어나는 곳을 살펴봅시다. server.js
파일입니다. server.js
는 일부 섹션으로 구성되며 시작 부분은 대부분 환경 변수에 대한 상수입니다. 그런 다음 두 개의 서버를 만듭니다. 하나는 httpServer
이고 다른 하나는 agServer
입니다. agServer
는 소켓을 처리합니다. httpServer
는 eetase으로 래핑된 HTTP 서버입니다. 기본적으로 요청에 대해 루프를 실행할 수 있도록 대기열에 요청을 추가합니다for await (let ... of asyncQueueIterable) { ...logic... }
. 그런 다음 익스프레스 부분이 나옵니다. 제공할 디렉토리를 정의하고 서버가 작동하는지 확인하기 위한 경로를 제공합니다/health-check
.
// HTTP request handling loop.
(async () => {
for await (let requestData of httpServer.listener('request')) {
expressApp.apply(null, requestData);
}
})();
이 코드 조각calls은 모든 요청을 expressApp
변수에 비동기적으로 요청하고 requestData를 첫 번째 인수로 전달하여 기본적으로 요청을 처리합니다. 여기서 eetase
는 요청을 대기열에 넣고 조심스럽게 하나씩 실행하는 데 유용합니다.
끝점을 만들어 봅시다
먼저 server.js
에 엔드포인트를 생성합니다. 이것은 모든 소켓 연결의 진입점입니다. 몇 가지 코드를 추가해 보겠습니다.
for await (let { socket } of agServer.listener('connection')) {
...
for await (let request of socket.procedure('test')) {
console.log(request.data);
request.end({ message: 'Data received, thanks client!' });
}
...
}
...
이것은 test
프로시저에 대한 모든 요청을 처리합니다. 제공된 데이터를 콘솔에 기록하고 Data received, thanks client!
메시지로 응답합니다.
이제 클라이언트에서 이 경로를 실제로 테스트하기 위한 코드를 추가해 보겠습니다. 기본 테스트를 수행할 수 있도록 index.html
폴더의 public
를 사용하겠습니다. HTML의 iframe
블록 아래에 버튼을 추가합니다.
...
<!-- IFRAME BLOCK -->
<button onclick="send()">Test</button>
...
그리고 아래에 일부 JavaScript 논리를 추가합니다let socket = socketClusterClient.create();
.
const send = async () => {
console.log('sending to the server...');
const response = await socket.invoke('test', {
message: 'This is our first message from the client to the server',
});
console.log(response);
};
서버를 다시 시작하고 localhost:8000 로 이동하여 개발자 콘솔을 열고 Test
버튼을 누르십시오. 클릭하면 브라우저에 Data received, thanks client!
가 표시되고 터미널로 이동하면 This is our first message from the client to the server
가 표시되어야 합니다.
이제 client
에서 server
까지 엔드포인트를 성공적으로 생성했습니다. 이제 몇 가지 멋진 일을 할 수 있지만 다른 방법으로도 할 수 있음을 보여 드리겠습니다. REST와 달리 SocketCluster를 사용하면 server
에서 client
로, client
에서 server
로 메시지를 처리할 수 있습니다. 클라이언트에 interval
를 보내는 간단한 예를 만들어 보겠습니다.
서버에서 10초의 interval
를 추가합니다.
...
const send = async () => {
console.log('sending to the server...')
const response = await socket.invoke(
'test',
{ message: 'This is our first message from the client to the server' },
);
console.log(response)
}
setInterval(async () => {
console.log('sending data to client...');
const data = await socket.invoke('from-server', {
message: 'This is sent from the server to the client',
});
console.log(data);
}, 10000);
...
그리고 클라이언트에서 절차를 듣습니다.
...
const send = async () => {
console.log('sending to the server...')
const response = await socket.invoke(
'test',
'This is our first message from the client to the server',
);
console.log(response)
}
(async () => {
for await (let request of socket.procedure('from-server')) {
console.log(request.data);
// return this message to the server, it could just be request.end() to terminate it
request.end({ message: 'Thanks server, message received' });
}
})();
...
서버를 다시 시작하고 브라우저 창을 새로 고칩니다. 10초마다 메시지This is sent from the server to the client
를 수신해야 합니다.
Reference
이 문제에 관하여(SocketCluster. 가장 과소평가된 프레임워크. 파트 2: 간단한 예), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/maartennnn/socketcluster-the-most-underrated-framework-part-2-setting-up-5b3o
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
NOTE
In this article I will focus solely on SocketCluster and not implement Vue yet. We will do some vanilla client js in the index.html
file served by SocketCluster.
// HTTP request handling loop.
(async () => {
for await (let requestData of httpServer.listener('request')) {
expressApp.apply(null, requestData);
}
})();
for await (let { socket } of agServer.listener('connection')) {
...
for await (let request of socket.procedure('test')) {
console.log(request.data);
request.end({ message: 'Data received, thanks client!' });
}
...
}
...
...
<!-- IFRAME BLOCK -->
<button onclick="send()">Test</button>
...
const send = async () => {
console.log('sending to the server...');
const response = await socket.invoke('test', {
message: 'This is our first message from the client to the server',
});
console.log(response);
};
...
const send = async () => {
console.log('sending to the server...')
const response = await socket.invoke(
'test',
{ message: 'This is our first message from the client to the server' },
);
console.log(response)
}
setInterval(async () => {
console.log('sending data to client...');
const data = await socket.invoke('from-server', {
message: 'This is sent from the server to the client',
});
console.log(data);
}, 10000);
...
...
const send = async () => {
console.log('sending to the server...')
const response = await socket.invoke(
'test',
'This is our first message from the client to the server',
);
console.log(response)
}
(async () => {
for await (let request of socket.procedure('from-server')) {
console.log(request.data);
// return this message to the server, it could just be request.end() to terminate it
request.end({ message: 'Thanks server, message received' });
}
})();
...
Reference
이 문제에 관하여(SocketCluster. 가장 과소평가된 프레임워크. 파트 2: 간단한 예), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/maartennnn/socketcluster-the-most-underrated-framework-part-2-setting-up-5b3o텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)