サーバーサイドロジックの実装
WebSocketサーバーを作成し、接続を待ち受け、基本的なイベントを処理するコードを書きます。
「サーバーサイドロジックの実装」はCoddyKit上の無料WebSockets & Realtime Systems Programmingレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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時間対応のAIチューター)、WebSockets & Realtime Systems Programmingコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 WebSockets & Realtime Systems Programmingコースには全4レッスンが含まれています。
「サーバーサイドロジックの実装」で何を学びますか?
WebSocketサーバーを作成し、接続を待ち受け、基本的なイベントを処理するコードを書きます。 ブラウザで直接実行するハンズオンコードでWebSockets & Realtime Systems Programmingを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
WebSockets & Realtime Systems Programmingを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのWebSockets & Realtime Systems Programmingは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「サーバーサイドロジックの実装」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このWebSockets & Realtime Systems Programmingレッスンでコードを書いて実行できますか?
はい。すべてのWebSockets & Realtime Systems Programmingレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- Node.jsプロジェクトのセットアップ
- サーバーサイドロジックの実装
- クライアントへのメッセージブロードキャスト
- ルームとチャネルの管理