From 0547039150b8606b6d9f683b1356642da56fbca3 Mon Sep 17 00:00:00 2001 From: Kohei Watanabe Date: Tue, 24 Mar 2020 19:14:17 +0900 Subject: [PATCH 1/2] Initial commit --- README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..d4dc3bc --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# socket-io-example +Created with CodeSandbox From ea8bce768f3f83264607b84db2fb2208ac105407 Mon Sep 17 00:00:00 2001 From: Kohei Watanabe Date: Tue, 24 Mar 2020 19:14:25 +0900 Subject: [PATCH 2/2] Initial commit --- README.md | 2 -- package.json | 17 +++++++++++++++ src/index.js | 19 ++++++++++++++++ src/public/index.html | 50 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 86 insertions(+), 2 deletions(-) delete mode 100644 README.md create mode 100644 package.json create mode 100644 src/index.js create mode 100644 src/public/index.html diff --git a/README.md b/README.md deleted file mode 100644 index d4dc3bc..0000000 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# socket-io-example -Created with CodeSandbox diff --git a/package.json b/package.json new file mode 100644 index 0000000..2aafb85 --- /dev/null +++ b/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/src/index.js b/src/index.js new file mode 100644 index 0000000..bda082d --- /dev/null +++ b/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/src/public/index.html b/src/public/index.html new file mode 100644 index 0000000..ffcfcb1 --- /dev/null +++ b/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; })
+

+ +