7
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

こんにちは、エンジニアのkeitaMaxです。

今回はSocket.IOってなに?ということでSocket.IOについて調べて実装してみたので記事にしようと思います。

Socket.IOってなに?

Bidirectional and low-latency communication for every platform
(引用:https://socket.io/)

Socket.IOは、リアルタイムの双方向通信を可能にするJavaScriptライブラリのことです。
WebSocketプロトコルをベースに、ブラウザとサーバー間で双方向のリアルタイム通信を簡単に実現できます。

公式サイト

クイックスタートやってみる

今回はNext.jsを使用して実装していきたいと思います。

Next.jsのセットアップについてはこの記事では解説しないので、以下の記事を参考にしてください。

socket.ioのインストール

以下のコマンドでインストールします。

npm install socket.io socket.io-client

実際に使用する

上の記事を参考に実装していきます。

├── components
│   └──Content.tsx
│
├── app
│   └── pages.tsx
│
└── pages
    └── api
        └── socket
            └── index.ts

components/Content.tsx
"use client"
import { useEffect } from "react"
import { io } from "socket.io-client"

const socket = io({ autoConnect: false })

export default function Content() {
    useEffect(() => {
        fetch("/api/socket", { method: "POST" })
            .then(() => {
                if (socket.connected) {
                    return
                }
                socket.connect()
                socket.on("connect", () => { console.log("connected!") })
                socket.on("msg", (msg) => { console.log(msg) })
            })

        return () => {
            socket.off("connect")
            socket.off("msg")
        }
    }, [])

    return (
        <>
            <h1>socket.io シンプルな接続例</h1>
        </>
    )
}
app/pages.tsx
import Content from "@/components/Content"
import type { Metadata } from "next"

export const metadata: Metadata = {
    title: "シンプルなsocket.io",
    description: "Next.jsでのシンプルなsocket.ioの接続例",
}

export default function Page() {
    return (
        <Content />
    )
}

pages/api/socket/index.ts
import { NextApiRequest, NextApiResponse } from "next"
import { Server, Socket } from "socket.io"
import { Server as IOServer } from 'socket.io'
import { Server as HTTPServer } from 'http'
import { Socket as NetSocket } from 'net'

type NextApiResponseWithSocket = NextApiResponse & {
    socket: NetSocket & {
        server: HTTPServer & {
            io: IOServer;
        };
    };
}


export default function handler(
    req: NextApiRequest,
    res: NextApiResponseWithSocket,
) {
    if (res.socket?.server.io) {
        return res.send("server is already running")
    }

    const io = new Server(res.socket.server, { addTrailingSlash: false })
    // 各イベントを設定
    io.on("connection", (socket: Socket) => {
        socket.on("disconnect", () => console.log("disconnected"))
        socket.emit("msg", "hello, from server!")
    })
    res.socket.server.io = io

    return res.end()
}

実行

下記コマンドで実行してアクセスしてみると、以下のように参考元と同じようにコンソールにサーバ側で送ったメッセージが表示されました。

npm run dev

スクリーンショット 2024-07-02 0.45.25.png

おわりに

この記事での質問や、間違っている、もっといい方法があるといったご意見などありましたらご指摘していただけると幸いです。

最後まで読んでいただきありがとうございました!

参考

7
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?