서버 측 로직 구현
WebSocket 서버를 만들고 연결을 수신하며 기본 이벤트를 처리하는 코드를 작성합니다.
서버 측 로직 구현은(는) CoddyKit의 무료 WebSockets & Realtime Systems Programming 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Realtime Systems Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Server Logic Unveiled
Welcome back! In the previous lesson, we set up our Node.js project. Now, let's dive into building the actual server logic for our WebSocket application.
We'll learn how to create a WebSocket server, listen for incoming client connections, and handle basic events like receiving and sending messages.
Creating the WS Server
The first step is to create an instance of our WebSocket server. We'll use the ws library we installed earlier. It provides a WebSocket.Server class.
We need to specify a port for our server to listen on. Port 8080 is a common choice for development.
Try running this basic server setup:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
console.log('WebSocket server started on port 8080');Listening for Connections
Our server is running, but it doesn't do much yet! The most fundamental event for a WebSocket server is 'connection'.
This event fires every time a new client successfully establishes a WebSocket connection with our server. The event handler receives a ws object, representing the individual client connection.
Let's add a handler to log when a client connects:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
console.log('Client connected!');
});
console.log('WebSocket server started on port 8080');The Client WebSocket Object
When a client connects, the wss.on('connection') callback receives a ws object. This isn't the server itself, but an instance of WebSocket specific to that client.
- It represents the communication channel with that single client.
- We'll use this
wsobject to send messages to, and receive messages from, that particular client.
Think of it as a direct line to one person in a crowded room.
Handling Client Messages
Once a client is connected, it can send messages to our server. We need to listen for these messages using the 'message' event on the individual client's ws object.
The message handler receives the data sent by the client. For simplicity, we'll assume text messages for now.
Update your server to log any incoming messages:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
console.log('Client connected!');
ws.on('message', function incoming(message) {
console.log('Received: %s', message);
});
});
console.log('WebSocket server started on port 8080');Sending Data Back to Client
A key aspect of WebSockets is bidirectional communication. Not only can clients send messages to the server, but the server can also send messages back to specific clients.
We use the ws.send() method on the client's WebSocket object to send data. Let's create a simple 'echo' server that sends back whatever it receives!
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
console.log('Client connected!');
ws.on('message', function incoming(message) {
console.log('Received: %s', message);
ws.send(`Server received: ${message}`); // Echo back!
});
});
console.log('WebSocket server started on port 8080');Handling Client Disconnections
Clients won't stay connected forever. They might close their browser tab, lose internet, or deliberately disconnect. It's crucial to handle these disconnections gracefully.
The 'close' event on the client's ws object tells us when a client has disconnected. This is useful for cleanup or logging.
Add a 'close' event handler to your server:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
console.log('Client connected!');
ws.on('message', function incoming(message) {
console.log('Received: %s', message);
ws.send(`Server received: ${message}`);
});
ws.on('close', function close() {
console.log('Client disconnected!');
});
});
console.log('WebSocket server started on port 8080');Dealing with Errors
Errors can occur at various stages ��� network issues, malformed messages, or server problems. It's good practice to include error handling.
- Client-specific errors: Use
ws.on('error', ...)for issues related to a single client connection. - Server-wide errors: Use
wss.on('error', ...)for problems affecting the entire WebSocket server.
Let's add basic error logging to our server:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
console.log('Client connected!');
ws.on('message', function incoming(message) {
console.log('Received: %s', message);
ws.send(`Server received: ${message}`);
});
ws.on('close', function close() {
console.log('Client disconnected!');
});
ws.on('error', function error(err) {
console.error('Client WS Error:', err.message);
});
});
wss.on('error', function serverError(err) {
console.error('Server WS Error:', err.message);
});
console.log('WebSocket server started on port 8080');Full Basic Server Example
You've now learned how to set up a WebSocket server, handle new connections, listen for incoming messages, send responses, and manage disconnections and errors.
This complete example brings all those concepts together, forming a robust foundation for your WebSocket applications.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
console.log('Client connected!');
ws.on('message', function incoming(message) {
console.log(`Received from client: ${message}`);
ws.send(`Echo: ${message}`); // Send message back to the same client
});
ws.on('close', function close() {
console.log('Client disconnected!');
});
ws.on('error', function error(err) {
console.error('Client connection error:', err);
});
});
wss.on('listening', () => {
console.log('WebSocket server is listening on port 8080');
});
wss.on('error', function serverError(err) {
console.error('WebSocket server error:', err);
});Server Logic Quiz
Which event handler is used on the server instance (wss) to detect when a new client connects?
Recap & Next Steps
Great work! You've successfully implemented the core server-side logic for a WebSocket application.
- You learned to create a
WebSocket.Serverinstance. - You handled
'connection','message','close', and'error'events. - You can now send messages back to individual connected clients using
ws.send().
Next, we'll explore how to send messages to ALL connected clients, a crucial feature for chat applications and other broadcast scenarios!
자주 묻는 질문
“서버 측 로직 구현” 강의는 무료인가요?
네 — “서버 측 로직 구현” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Realtime Systems Programming 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“서버 측 로직 구현”에서 뭘 배우나요?
WebSocket 서버를 만들고 연결을 수신하며 기본 이벤트를 처리하는 코드를 작성합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Realtime Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
WebSockets & Realtime Systems Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Realtime Systems Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“서버 측 로직 구현” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 WebSockets & Realtime Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 WebSockets & Realtime Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Node.js 프로젝트 설정
- 서버 측 로직 구현
- 클라이언트에 메시지 브로드캐스트
- 방과 채널 관리