From 62771d577747f8c40ac337d6c6fbaac2db1f1a76 Mon Sep 17 00:00:00 2001 From: danaisboss Date: Wed, 4 Aug 2021 17:08:17 +0900 Subject: [PATCH] =?UTF-8?q?Update,=20socket.js=20=EC=BD=94=EB=93=9C?= =?UTF-8?q?=EB=B6=84=EB=A6=AC,=20server/app=20=EB=B6=84=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.js | 16 +++--- server.js | 9 ++++ socket.js | 140 ++++++++++++++++++++++++------------------------- socket.spec.js | 43 +++++++++++++++ socket.test.js | 89 +++++++++++++++++++++++++++++++ 5 files changed, 220 insertions(+), 77 deletions(-) create mode 100644 server.js create mode 100644 socket.spec.js create mode 100644 socket.test.js diff --git a/app.js b/app.js index f0e0b9e..a13c28f 100644 --- a/app.js +++ b/app.js @@ -1,16 +1,16 @@ // main 연결페이지 const express = require("express"); -const app = express(); const dotenv = require("dotenv"); dotenv.config(); const cron = require("node-cron"); +const Http = require("http"); const helmet = require("helmet"); const path = require("path"); const passport = require("passport"); const passportConfig = require("./middlewares/passport"); -const port = process.env.EXPRESS_PORT; -const webSocket = require("./socket"); +const app = express(); +const http = Http.createServer(app); // DB연결 const mongoose = require("mongoose"); const connect = require("./schema/dbConnect"); @@ -49,8 +49,10 @@ app.use("/product", productRouter); app.use("/user", userRouter); app.use("/bid", socketRouter); -const server = app.listen(port, () => { - console.log(`Server start at http://localhost:${port}`); -}); +module.exports = http; + +// const server = app.listen(port, () => { +// console.log(`Server start at http://localhost:${port}`); +// }); -webSocket(server); +// webSocket(server); diff --git a/server.js b/server.js new file mode 100644 index 0000000..4abd6f4 --- /dev/null +++ b/server.js @@ -0,0 +1,9 @@ +const http = require("./app"); +const port = process.env.EXPRESS_PORT; +const dotenv = require("dotenv"); +dotenv.config(); +require("./socket"); + +http.listen(port, () => { + console.log(`Server start at http://localhost:${port}`); +}); diff --git a/socket.js b/socket.js index 7d3851f..e0df72c 100644 --- a/socket.js +++ b/socket.js @@ -1,77 +1,77 @@ -//socketIo 모듈을 불러오기 -module.exports = (server) => { - const SocketIO = require("socket.io"); - const Chat = require("./schema/chathistory"); - const io = SocketIO(server, { - cors: { - origin: "*", - methods: ["GET", "POST"], - }, - }); +const SocketIO = require("socket.io"); +const http = require("./app"); +const io = SocketIO(http, { + cors: { + origin: "*", + methods: ["GET", "POST"], + }, +}); + +const chatSpace = io.of("/chat"); +const globalSpace = io.of("/global"); + +chatSpace.on("connection", (socket) => { + const { watchJoin, watchSend, watchByebye } = initSocket(socket); - const chatSpace = io.of("/chat"); - const globalSpace = io.of("/global"); + watchJoin(); + watchSend(); + watchByebye(); +}); - //logic - chatSpace.on("connection", async (socket) => { - // user join - socket.on("join", async (data) => { - const req = socket.request; - const { room, username } = data; - socket.join(room); //특정 방에 접속하는 코드 - const chats = await Chat.find({ room }); - chatSpace.to(room).emit("load", chats); - }); - // send message - socket.on("send", async (data) => { - const { room } = data; - const content = new Chat({ - room, - productId: data.product, - msg: data.msg, - user: data.username, - time: Date.now(), +const initSocket = (socket) => { + console.log("새로운 소켓이 연결되었습니다."); + function watchEvent(event, func) { + socket.on(event, func); + } + + function notifyToChat(event, data) { + console.log("데이터를 emit합니다."); + chatSpace.emit(event, data); + } + + function notifyToRoom(event, data) { + console.log("room에 emit합니다."); + const { room } = data; + chatSpace.to(room).emit(event, data); + } + return { + // 특정 room에 join + watchJoin: () => { + watchEvent("join", async (data) => { + const Chat = require("./schema/chathistory"); + const { room } = data; + socket.join(room); + const chats = await Chat.find({ room }); + console.log("Hello watchJoin!"); + console.log(socket.rooms.size); + notifyToChat("load", chats); }); - if (data.room === `${undefined}-${undefined}-${undefined}`) { - content.msg = "거래 이후 채팅 가능합니다."; - } - //챗봇 - else if (data.product === "1") { - if (data.msg.includes("사용법")) { - content.msg = - "오타쿠 굿즈를 판매하고싶다면, \n왼쪽 상단의 물건등록을 눌러주세요.\n 구매하려면 경매물품을 최고가에 입찰해봅시다!"; - } - if (data.msg.includes("신고")) { - content.msg = - "현재 신고관련 기능은 준비중입니다. \n경매 물건의 이름과 신고대상의 닉네임을\n itsoku@naver.com 으로 보내주시면 확인 후 블락하고있습니다."; - } - if (data.msg.includes("개발자")) { - content.msg = - "저희에게 관심이 있으시다구요?! https://www.notion.so/90bbb2e5d07941a3a46370e5333c7556"; - } - if (data.msg.includes("건의")) { - content.msg = - "어떤점이 불편하셨나요? itsoku@naver.com 으로 보내주시면 귀담아 듣겠습니다."; - } - } else { - await content.save(); - } + }, - // 저장한 데이터를 클라이언트에게 receive라는 emit으로 전송 - chatSpace.to(room).emit("receive", content); - //접속해제 시 방을 떠나는 코드 - socket.on("disconnect", () => { - console.log("chat 네임스페이스 접속 해제"); - socket.leave(room); + // send a message + watchSend: () => { + watchEvent("send", async (data) => { + const Chat = require("./schema/chathistory"); + const { room } = data; + const content = new Chat({ + room, + productId: data.product, + msg: data.msg, + user: data.username, + time: Date.now(), + }); + await content.save(); + notifyToChat("receive", content); }); - }); - }); + }, - //global socket 알림, 채팅 목록 - globalSpace.on("connection", function (socket) { - socket.on("globalSend", async function (data) { - console.log(data); - globalSpace.emit("globalReceive", data); - }); - }); + // room leave + watchByebye: () => { + watchEvent("disconnect", () => { + console.log("chatSpace 접속 해제"); + // room leave가 성공적으로 되었을 때 아래 콘솔 값 === 0 + console.log(socket.rooms.size); + }); + }, + }; }; diff --git a/socket.spec.js b/socket.spec.js new file mode 100644 index 0000000..aff6113 --- /dev/null +++ b/socket.spec.js @@ -0,0 +1,43 @@ +const { createServer } = require("http"); +const { Server } = require("socket.io"); +//const Client = require("socket.io-client"); +const assert = require("chai").assert; + +describe("my awesome project", () => { + let io, serverSocket, clientSocket; + + before((done) => { + const httpServer = createServer(); + io = new Server(httpServer); + httpServer.listen(() => { + const port = httpServer.address().port; + clientSocket = new Client("http://localhost:9090"); + io.on("connection", (socket) => { + serverSocket = socket; + }); + clientSocket.on("connect", done); + }); + }); + after(() => { + io.close(); + clientSocket.close(); + }); + + it("should work", (done) => { + clientSocket.on("hello", (arg) => { + assert.equal(arg, "world"); + done(); + }); + serverSocket.emit("hello", "world"); + }); + + it("should work (with ack)", (done) => { + serverSocket.on("hi", (cb) => { + cb("hola"); + }); + clientSocket.emit("hi", (arg) => { + assert.equal(arg, "hola"); + done(); + }); + }); +}); diff --git a/socket.test.js b/socket.test.js new file mode 100644 index 0000000..104cb11 --- /dev/null +++ b/socket.test.js @@ -0,0 +1,89 @@ +//socketIo 모듈을 불러오기 +module.exports = (server) => { + const SocketIO = require("socket.io"); + const Chat = require("./schema/chathistory"); + const io = SocketIO(server, { + cors: { + origin: "*", + methods: ["GET", "POST"], + }, + }); + + const chatSpace = io.of("/chat"); + const globalSpace = io.of("/global"); + + const initSocket = (socket) => { + console.log("새로운 소켓이 연결되었습니다."); + function watchEvent(event, func) { + socket.on(event, func); + } + function notifyToClient(event, data) { + io.emit(event, data); + } + + return { + watchJoin: () => { + watchEvent("join", (data) => {}); + }, + watchSend: () => { + notifyToClient("send", (data) => { + const { room } = data; + const content = new Chat({ + room, + productId: data.product, + msg: data.msg, + user: data.username, + time: Date.now(), + }); + if (data.room === `${undefined}-${undefined}-${undefined}`) { + content.msg = "거래 이후 채팅 가능합니다."; + } + //챗봇 + else if (data.product === "1") { + if (data.msg.includes("사용법")) { + content.msg = + "오타쿠 굿즈를 판매하고싶다면, \n왼쪽 상단의 물건등록을 눌러주세요.\n 구매하려면 경매물품을 최고가에 입찰해봅시다!"; + } + if (data.msg.includes("신고")) { + content.msg = + "현재 신고관련 기능은 준비중입니다. \n경매 물건의 이름과 신고대상의 닉네임을\n itsoku@naver.com 으로 보내주시면 확인 후 블락하고있습니다."; + } + if (data.msg.includes("개발자")) { + content.msg = + "저희에게 관심이 있으시다구요?! https://www.notion.so/90bbb2e5d07941a3a46370e5333c7556"; + } + if (data.msg.includes("건의")) { + content.msg = + "어떤점이 불편하셨나요? itsoku@naver.com 으로 보내주시면 귀담아 듣겠습니다."; + } + } else { + await content.save(); + } + // 클라이언트에게서 받은 메세지 emit + chatSpace.to(room).emit("receive", content); + }); + }, + watchDisconnect: () => { + watchEvent("disconnect", () => { + console.log("chat 네임스페이스 접속 해제"); + }); + }, + }; + }; + //logic + chatSpace.on("connection", async (socket) => { + const { watchJoin, watchSend, watchDisconnect } = initSocket(socket); + + watchJoin(); + watchSend(); + watchDisconnect(); + }); + + //global socket 알림, 채팅 목록 + globalSpace.on("connection", function (socket) { + socket.on("globalSend", async function (data) { + console.log(data); + globalSpace.emit("globalReceive", data); + }); + }); +};