タイトル : WebSocketを試す 1st 2025
更新日 : 2025-05-11
カテゴリ : プログラミング
タグ :
websocket   
nodejs   

概要

受信はPOSTで、送信はWebSocketを使う例を試してみたくて、express,wsでやってみます。

Server

準備

npm install express ws
npm install @types/express @types/ws @types/node
npm install vite-node

ソース

import express, { Request, Response } from 'express';
import { WebSocketServer, WebSocket } from 'ws';
import http from 'http';

const app = express();
const port = 3000;

// HTTPサーバーの作成
const server = http.createServer(app);

// WebSocketサーバーの作成
const wss = new WebSocketServer({ server });

// 接続中のクライアントを保持するSet
const clients = new Set<WebSocket>();

// WebSocket接続時の処理
wss.on('connection', ws => {
  console.log('Client connected');
  clients.add(ws);

  // クライアントが切断した時の処理
  ws.on('close', () => {
    console.log('Client disconnected');
    clients.delete(ws);
  });

  // クライアントからのメッセージ受信時の処理(ここでは特に何もしていません)
  ws.on('message', message => {
    console.log(`Received message from a client: ${message}`);
  });

  // エラー処理
  ws.on('error', error => {
    console.error(`WebSocket error: ${error}`);
    clients.delete(ws);
  });
});

// POSTリクエストを受け付けるエンドポイント
app.use(express.json()); // JSON形式のRequestBodyを解析するmiddleware

app.post('/data', (req: Request, res: Response) => {
  const receivedData = req.body;
  console.log('Received data via POST:', receivedData);

  // 接続中の全てのクライアントにデータを送信
  clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(JSON.stringify(receivedData));
    }
  });

  res.sendStatus(200); // POSTリクエストが成功したことをクライアントに通知
});

// サーバーを起動
server.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

Client

準備

npm install ws
npm install @types/ws
npm install vite-node

ソース

import WebSocket from "ws";

// 接続先のURL
const url = "ws://localhost:3000";
// WebSocketクライアントを作成
const ws = new WebSocket(url);

// open イベントは、 WebSocket のコネクションが開かれたときに発生します
ws.onopen = () => {
  console.log("Connected to the server.");
};

// onmessage イベントは、WebSocketからメッセージを受信したときに発生します。
ws.onmessage = (e) => {
  console.log(`Received: ${e.data}`);
};

// onerror イベントは、WebSocketのエラーが発生したときに発生します。
ws.onerror = (error) => {
  console.error(`WebSocket Error: ${error}`);
};

// oncloseは、WebSocketのコネクションが閉じられたときに発生します。
ws.onclose = () => {
  console.log("Disconnected from the server");
};

実行例

サーバー

$ npx vite-node server.ts
Server listening on port 3000
Client connected
Client connected
Received data via POST: { message: 'Hello from POST 1' }

クライアント

$ npx vite-node client.ts
Connected to the server.
Received: {"message":"Hello from POST 1"}

POST

$ curl -X POST -H "Content-Type: application/json" -d '{"message": "Hello from POST 1"}' http://localhost:3000/data
OK
$ 

URLS

Node.js と ws でシンプルな WebSocketサーバー + Node.js v22 でフラグなしで使える WebSocket https://qiita.com/youtoy/items/9e1eeae728dc98f15679

2024最新:Node.jsでWebSocketを利用する https://apidog.com/jp/blog/nodejs-websocket/

WebSocket(ブラウザAPI)とws(Node.js) の基本、自分用のまとめ https://qiita.com/okumurakengo/items/c497fba7f16b41146d77

TypeScript で WebSocket サーバを立てる https://zenn.dev/hayato94087/articles/f568bdf5eae6c4

WebSocket についてまとめてみる https://qiita.com/att55/items/da663f6e713c3bd073e8

WebSocket 入門 https://zenn.dev/nameless_sn/articles/websocket_tutorial

ReactでWebSocketを扱う https://qiita.com/_ytori/items/a92d69760e8e8a2047ac

これからWebSocketを導入しようと考える前に読んでほしい https://zenn.dev/dove/articles/9c869cd46e1a5a

React HooksでWebSocket通信を行うサンプル https://qiita.com/yonetty/items/acc46afa59da1796a767

PythonでWebSocketのサンプル https://zenn.dev/kun432/scraps/91f2dfa6daa79a

Python websocketsの疑問点まとめ https://qiita.com/yakiimo121/items/7c2ef941a301f5c16153

Pythonのwebsocket-clientを使ってみた https://blog.serverworks.co.jp/2024/06/05/104322

FastAPIでWebSocket入門 https://qiita.com/Katsuya_Ogata/items/1f321f6d9fc14fcd4607

FastAPIでWebSocketが使用できます。 https://fastapi.tiangolo.com/ja/advanced/websockets/

FastAPIでWebSocketに入門してみた https://zenn.dev/knot/articles/dbce3e3a2f3f3a