-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Update, socket.js 코드분리, server/app 분리
- Loading branch information
Showing
5 changed files
with
220 additions
and
77 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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}`); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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); | ||
}); | ||
}, | ||
}; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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(); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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); | ||
}); | ||
}); | ||
}; |