diff --git a/socketio/package.json b/socketio/package.json new file mode 100644 index 0000000..2aafb85 --- /dev/null +++ b/socketio/package.json @@ -0,0 +1,17 @@ +{ + "name": "socket-io-example", + "version": "1.0.0", + "description": "", + "main": "src/index.js", + "scripts": { + "start": "nodemon src/index.js" + }, + "dependencies": { + "express": "4.17.1", + "socket.io": "2.3.0" + }, + "devDependencies": { + "nodemon": "1.18.4" + }, + "keywords": [] +} \ No newline at end of file diff --git a/socketio/src/index.js b/socketio/src/index.js new file mode 100644 index 0000000..bda082d --- /dev/null +++ b/socketio/src/index.js @@ -0,0 +1,19 @@ +// @ts-check +const path = require("path"); +const app = require("express")(); +const http = require("http").createServer(app); +const io = require("socket.io")(http); + +const port = Number(process.env.PORT) || 8080; + +app.get("/", function(_, res) { + res.sendFile(path.join(__dirname, "public", "index.html")); +}); + +http.listen(port, function() { + console.log(`listening on http://localhost:${port}`); +}); + +io.on("connect", socket => { + socket.on("message", message => io.send(message)); +}); diff --git a/socketio/src/public/index.html b/socketio/src/public/index.html new file mode 100644 index 0000000..ffcfcb1 --- /dev/null +++ b/socketio/src/public/index.html @@ -0,0 +1,50 @@ + + + + + + Demo + + + + +

+
+ +
+

+ Developer Tools のコンソール (Ctrl+Shift+J や Cmd+Opt+J) を開いて次のコードを実行する: +

+ メッセージを送るためのコードの例: +

io().send("こんにちは")
+

+

+ メッセージを受け取るためのコードの例: +

io().on("message", message => { document.body.textContent = message; })
+

+ +