2025年10月24日金曜日

積み残し Websocket chat (node.js,python3)

https://qiita.com/shun_sakamoto/items/7944d0ac4d30edf91fde

venvで手軽にPythonの仮想環境を構築しよう 

以下のエラー対策は仮想環境しかない!

pip3 install asyncio error: externally-managed-environment

× This environment is externally managed

. env/bin/activate ./env/bin/pip3 install asyncio で成功!

---------------------------------------------

https://qiita.com/youtoy/items/f74e4ae26a1b67c310c0 :: simple websocket echo server

--------------------echo server----------
import asyncio
import websockets

async def echo(websocket, path):
    print("クライアントが接続しました")
    try:
        async for message in websocket:
            print(f"受信: {message}")
            response = f"Echo: {message}"
            await websocket.send(response)
            print(f"送信: {response}")
    except websockets.exceptions.ConnectionClosed:
        print("クライアントとの接続が閉じられました")

async def main():
    # localhost の 8765 番ポートでサーバーを起動
    async with websockets.serve(echo, "localhost", 8765):
        print("WebSocketサーバーが起動しました")
        await asyncio.Future()  # 永久に待機

if __name__ == '__main__':
    asyncio.run(main())
-----------------------------------------------------
https://qiita.com/youtoy/items/ae1dd6ee36ac35c6e519 より
-----------------------client.py------------------------------------
import asyncio
from websockets.asyncio.client import connect

async def hello():
    async with connect("ws://localhost:8765") as websocket:
        await websocket.send("Hello world!")
        message = await websocket.recv()
        print(message)


if __name__ == "__main__":
    asyncio.run(hello())

https://qiita.com/youtoy/items/ae1dd6ee36ac35c6e519 はブロードキャスサーバもあり
ーーーーーーーーー

https://qiita.com/hikichi_shoto/items/f976970a114bab20325a flaskでチャット、有益
192.168.11.8:5002でアクセスしてチャットができた!

------------------------------------------------------------

Node.jsでWebSocketサーバーを実装するには、wsのようなライブラリを使用します。このライブラリを使うと、クライアントの接続を待ち受け、接続されたクライアントと双方向でメッセージの送受信ができます。

サーバー側の実装(Node.js)
  1. ライブラリのインストール:
まず、wsライブラリをインストールします。
ソースコード
    npm install ws
  1. サーバーの作成と起動:
以下のコードをserver.jsなどのファイルに保存します。
JavaScript
    const WebSocket = require('ws');    // WebSocketサーバーをポート8080で起動します
    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);
        // 受信したメッセージを全クライアントにブロードキャストする例        wss.clients.forEach(function each(client) {
          if (client !== ws && client.readyState === WebSocket.OPEN) {
            client.send(`Broadcasting: ${message}`);          }        });      });      // 接続時の処理      ws.send('Something');      // 接続終了時の処理
      ws.on('close', () => {        console.log('Client disconnected');
      });
    });    console.log('WebSocket server started on port 8080');
クライアント側の実装(JavaScript)
ブラウザの開発者ツールや、HTMLとJavaScriptでクライアントを作成します。
ソースコード
<!DOCTYPE html><html><head>  <title>WebSocket Client</title></head><body>  <input type="text" id="messageInput" placeholder="メッセージを入力">
  <button id="sendButton">送信</button>
  <div id="output"></div>
  <script>
    const output = document.getElementById('output');    const messageInput = document.getElementById('messageInput');    const sendButton = document.getElementById('sendButton');    // WebSocketサーバーに接続    const ws = new WebSocket('ws://localhost:8080');    // 接続が成功した時の処理
    ws.onopen = () => {      output.innerHTML += '<p>WebSocket Connected</p>';    };    // サーバーからメッセージが送られてきた時の処理
    ws.onmessage = (event) => {      output.innerHTML += `<p>Received: ${event.data}</p>`;    };    // 接続が閉じた時の処理    ws.onclose = () => {      output.innerHTML += '<p>WebSocket Disconnected</p>';    };    // サーバーにメッセージを送信する関数    function sendMessage() {      const message = messageInput.value;
      ws.send(message);      output.innerHTML += `<p>Sent: ${message}</p>`;      messageInput.value = ''; // 入力欄をクリア    }    // 送信ボタンクリック時のイベント    sendButton.addEventListener('click', sendMessage);    // Enterキーを押したときに送信    messageInput.addEventListener('keypress', function(event) {      if (event.key === 'Enter') {        sendMessage();      }    });  </script>
</body></html>

0 件のコメント:

コメントを投稿