Commit a47d81b4 authored by Choi Ga Young's avatar Choi Ga Young
Browse files

Merge remote-tracking branch 'origin/yeonwoo' into young

parents d3329f24 b9658194
......@@ -12,6 +12,7 @@ const INIT_CHAT = {
img: '',
time: ''
}
function Chat(props) {
//const [sender, setSender] = useState([])
......@@ -44,7 +45,8 @@ function Chat(props) {
e.preventDefault()
setInner(e.target.value)
setDisabled(false)
//console.log(chat)
console.log(props.leftInfo)
}
function sendMsgCH(e) {
......@@ -57,17 +59,35 @@ function Chat(props) {
props.sendMsg(e)
setInner('')
setDisabled(true)
recordEntryLog() //그냥 새로고침해도 최신화
}
async function recordEntryLog() {
const leaveInfo = { userId: userId, roomCode: props.roomCode, leaveTime: realTime }
try {
const check = await axios.get('/room/entrylog', { params: leaveInfo })
if (check.data) { //있으면 put으로
await axios.put('/room/entrylog', leaveInfo)
} else { //없으면 post
await axios.post('/room/entrylog', leaveInfo)
}
} catch (error) {
catchErrors(error, setError)
}
}
function handleClick() {
props.closeChatRoom(props.roomCode)
props.setRecievedMsg('')
props.handleChatc()
props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
console.log('나간시간', realTime, usualTime)
setChat([''])
props.handleChatc()
props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
recordEntryLog()
props.setRoomCode('')
}
function settingtime(hour) {
......@@ -88,7 +108,6 @@ function Chat(props) {
//프사 닉네임 메세지가 각각의 배열로 들어가서 띄워지는 방식
async function getPreviousChat() {
const respond = await axios.get('/room/getChatInfo', { params: { 'roomCode': props.roomCode } })
console.log(respond)
const info = respond.data
let intochat = []
......@@ -120,7 +139,6 @@ function Chat(props) {
useEffect(() => {
getPreviousChat()
// console.log('겟 룸네임', chat)
}, [props.roomCode])
......
import React from 'react'
import { Badge, ListGroup } from 'react-bootstrap';
import "../Pages/Home.css";
import axios from 'axios'
import catchErrors from '../utils/catchErrors';
const INIT_LIST = [{
interest: '',
isOpen: '',
memeber: [],
roomId: '',
roomName: '',
}]
function ClosedList(props) {
const [error, setError] = useState('')
const realTime = new Date().toISOString()
async function recordEntryLog(e) {
const leaveInfo = { userId: props.userId, roomCode: e.target.name, leaveTime: realTime }
try {
const check = await axios.get('/room/entrylog', { params: leaveInfo })
if (check.data) { //있으면 put으로
await axios.put('/room/entrylog', leaveInfo)
} else { //없으면 post
await axios.post('/room/entrylog', leaveInfo)
}
} catch (error) {
catchErrors(error, setError)
}
}
function enterChatRoomCH(e) {
async function enterChatRoomCH(e) {
if (props.roomCode) {
props.closeChatRoom(props.roomCode)
}
......@@ -21,43 +33,35 @@ function ClosedList(props) {
props.setRoomCode(roomCode)
props.setRoomName(roomName)
// console.log('rrrrrrrrrrrrrrr', props.closedlist)
// console.log('1111111111111111111', props.leaveInfo, typeof (props.leaveInfo))
await recordEntryLog(e) //방 입장시 시간 업데이트 (그래야 안 읽은 메세지가 0개로 되니까)
props.unreadMessage() //방 입장시 메세지 개수 다시셈 (그래야 입장시 0으로 초기화 되니까)
}
// const [checknew, setChecknew] = useState([])
// const [unreadnumber, setUnreadnumber] = useState([''])
// async function dbChat() {
// for (let i = 0; i <= props.closedlist.length - 1; i++) {
// const respond = await axios.get('/room/dbChat', { params: { 'roomId': props.closedlist[i].roomId } })
// setChecknew(respond.data)
// }
// }
// useEffect(() => {
// dbChat()
// }, [props.singleChat, props.recievedMsg])
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//안읽은 메세지 count하는 부분
// useEffect(() => {
// // console.log('chat 클라이언트 변경!')
// unreadMessage()
// }, [checknew])
useEffect(() => { // 누군가 보내면 다시 개수 셈
console.log('chat 클라이언트 변경!')
props.unreadMessage()
console.log('새 메세지가 도착했습니다.',props.leftInfo)
}, [props.checknew])
// async function unreadMessage() {
// //여기서 나간시간과 db의 메세지와 시간비교해서 개수를 count해주면 됨
// //물론 그 방 별로 찾아서 list를 맵써서 하던?
// // console.log('ddddddddd', list[0].roomId)
useEffect(() => { //일단 들오면 실행해야지
props.unreadMessage()
}, [props.closedlist])
// setUnreadnumber([''])
// let arr = []
// for (let i = 0; i <= props.closedlist.length - 1; i++) {
// const respond = await axios.get('/room/unreadMessage', { params: { 'leaveInfo': props.leaveInfo, 'roomId': props.closedlist[i].roomId } })
// // setUnreadnumber([...unreadnumber, respond.data])
// arr = [...arr, respond.data]
// }
// setUnreadnumber(arr)
// // console.log('클라이언트 클로즈드 카운드', unreadnumber, list.length)
// }
let count=[]
const [unread, setUnread] = useState([])
useEffect(() => { //unread정보가 들어오면 재정비해서 뿌려주기 위한 작업!
for (let i = 0; i < props.unreadnumber.length; i++) {
count.push(props.unreadnumber[i].unreadcount)
}
setUnread(count)
}, [props.unreadnumber])
return (
<div>
......@@ -66,7 +70,7 @@ function ClosedList(props) {
<ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId} value={item.roomName}
className='rounded-0'>
{item.roomName}
{/* {[index] ? <Badge className='ml-2' pill variant='danger'>{unreadnumber[index]}</Badge> : ''} */}
{unread[index] ? <Badge className='ml-2' pill variant='danger'>{unread[index]}</Badge> : ''}
</ListGroup.Item>
</ListGroup>
)
......
import React, { useState, useEffect } from 'react';
import { Row, Col, Button, Tabs, Tab } from 'react-bootstrap';
import { Row, Col, Button, Tabs, Tab, Form } from 'react-bootstrap';
import styled from 'styled-components';
import ClosedList from '../Components/ClosedList';
import OpenList from '../Components/OpenList';
......@@ -26,11 +26,18 @@ const INIT_LIST = [{
roomId: '',
roomName: '',
}]
const INIT_UNREAD = {
roomCode: '',
unreadcount: '',
}
function Home() {
const userName = sessionStorage.getItem('name')
const userId = sessionStorage.getItem('userId')
const [checknew, setChecknew] = useState('')
const [unreadnumber, setUnreadnumber] = useState(INIT_UNREAD)
const [showModal, setShowModal] = useState(false);
const [showEnter, setShowEnter] = useState(false);
const [chat, setChat] = useState(false);
......@@ -53,7 +60,6 @@ function Home() {
const [singleTime, setSingleTime] = useState('')
const [recievedTime, setRecievedTime] = useState('')
const [leaveInfo, setLeaveInfo] = useState([{ roomName: "", leaveTime: "" }])
const handleCloseModal = () => {
setShowModal(false);
......@@ -77,6 +83,7 @@ function Home() {
console.log(`joinRoom : ${rCode} 입장`)
console.log('show:', show)
//여기서 채팅 불러와서 넘겨주던가 해야할거 같은데
console.log('HomePage/enterChatRoom 끝났습니다')
}
function closeChatRoom(rCode) {
......@@ -84,6 +91,7 @@ function Home() {
console.log(`${rCode}방 보기 중단`)
}
async function exitRoom(roomId) {
const response = await axios.get('/users/check', { params: { '_id': userId } })
const userNick = response.data.nickname;
......@@ -95,6 +103,7 @@ function Home() {
async function getClosedList() {
const userid = sessionStorage.getItem('userId')
let res = await axios.get('/room/closedlist', { params: { '_id': userid } })
// console.log('getClosedList',res.data)
setClosedList(res.data)
}
......@@ -164,13 +173,48 @@ function Home() {
}
}, [sysmsg])
const INIT_LEFT = {
userId: '',
roomCode: '',
now: '',
}
const [leftInfo, setLeftInfo] = useState(INIT_LEFT)
async function unreadMessage() {
const userId = sessionStorage.getItem('userId')
let leaveInfo = []
try {
for (let i = 0; i < closedlist.length; i++) {
leaveInfo.push({ userId: userId, roomCode: closedlist[i].roomId, now: 0 })
}
for (let i = 0; i < closedlist.length; i++) {
if (leaveInfo[i].roomCode === roomCode) {
leaveInfo[i].now = '보는중'
} else {
leaveInfo[i].now = 0
}
}
setUnreadnumber([''])
const respond = await axios.get('/room/unreadMessage', { params: leaveInfo })
setUnreadnumber(respond.data)
setLeftInfo(leaveInfo)
} catch (error) {
console.log(error)
}
}
useEffect(() => {
socket.on("sendedMSG", (sendInfo) => {
setRecievedTime(sendInfo.time)
setRecievedImg(sendInfo.img)
setRecievedUser(sendInfo.sender)
setRecievedMsg(sendInfo.msg)
console.log(sendInfo.msg)
})
socket.on('checking', (check) => {
console.log('클라이언트', check)
setChecknew(check)
})
}, [])
......@@ -182,7 +226,7 @@ function Home() {
<Sdiv chat={chat}>
<Tabs defaultActiveKey="closed" id="uncontrolled-tab-example" >
<Tab eventKey="closed" title="내 채팅" onClick={handleChato} >
<ClosedList closedlist={closedlist} singleChat={singleChat} recievedMsg={recievedMsg} leaveInfo={leaveInfo} setLeaveInfo={setLeaveInfo} enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} closeChatRoom={closeChatRoom} />
<ClosedList closedlist={closedlist} leftInfo={leftInfo} checknew={checknew} unreadMessage={unreadMessage} unreadnumber={unreadnumber} setUnreadnumber={setUnreadnumber} userId={userId} singleChat={singleChat} recievedMsg={recievedMsg} enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} closeChatRoom={closeChatRoom} />
</Tab>
<Tab eventKey="open" title="공개방" onClick={handleChatc}>
<OpenList openlist={openlist} enterChatRoom={enterChatRoom} openListroom={openListroom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} closeChatRoom={closeChatRoom} />
......@@ -192,7 +236,7 @@ function Home() {
</Col>
<Col style={{ padding: "5px", marginLeft: "15px" }}>
{show ? <>
{chat ? <Chat handleChatc={handleChatc} leaveInfo={leaveInfo} setLeaveInfo={setLeaveInfo} sendMsg={sendMsg} singleChat={singleChat} singleUser={singleUser} singleImg={singleImg} singleTime={singleTime} recievedMsg={recievedMsg} recievedUser={recievedUser} recievedImg={recievedImg} recievedTime={recievedTime} setSingleChat={setSingleChat} setSingleUser={setSingleUser} setSingleImg={setSingleImg} setSingleTime={setSingleTime} setRecievedMsg={setRecievedMsg} roomCode={roomCode} roomName={roomName} closeChatRoom={closeChatRoom} exitRoom={exitRoom} />
{chat ? <Chat leftInfo={leftInfo} setLeftInfo={setLeftInfo} handleChatc={handleChatc} leaveInfo={leaveInfo} setLeaveInfo={setLeaveInfo} sendMsg={sendMsg} singleChat={singleChat} singleUser={singleUser} singleImg={singleImg} singleTime={singleTime} recievedMsg={recievedMsg} recievedUser={recievedUser} recievedImg={recievedImg} recievedTime={recievedTime} setSingleChat={setSingleChat} setSingleUser={setSingleUser} setSingleImg={setSingleImg} setSingleTime={setSingleTime} setRecievedMsg={setRecievedMsg} roomCode={roomCode} roomName={roomName} closeChatRoom={closeChatRoom} exitRoom={exitRoom} />
: <div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
<Button style={{ borderColor: "#9174ad", backgroundColor: "#9174ad", color: 'white' }} onClick={handleShowModal} size="lg" block>생성</Button>
<Button style={{ borderColor: "#9174ad", backgroundColor: "#9174ad", color: 'white' }} onClick={handleShowEnter} size="lg" block>참가</Button>
......
......@@ -19,6 +19,7 @@ function ProfilePage() {
const [hidden, setHidden] = useState(true)
const [changed, setChanged] = useState(false)
const [selectedImg, setSelectedImg] = useState('')
const userId = isAuthenticated()
......@@ -39,6 +40,7 @@ function ProfilePage() {
setHidden(true)
}
}
function handleChange(e) {
const { name, value, files } = e.target
if (files) {
......@@ -47,6 +49,14 @@ function ProfilePage() {
setUser({ ...user, [name]: value })
}
setChanged(true)
if (files) {
let reader = new FileReader()
reader.onload = function (e) {
setSelectedImg(e.target.result)
}
reader.readAsDataURL(e.target.files[0])
}
}
async function handleSubmit(e) {
e.preventDefault()
......@@ -75,6 +85,8 @@ function ProfilePage() {
getProfile(userId)
}, [userId])
return (
<>
<Menu />
......@@ -82,7 +94,8 @@ function ProfilePage() {
<Row >
<Col sm={4}>
<Row className='justify-content-center'>
<Image src={user.profileimg && `/images/${user.profileimg}`} style={{ width: "300px", height: "300px" }} roundedCircle />
{!selectedImg ? <Image src={user.profileimg && `/images/${user.profileimg}`} style={{ width: "300px", height: "300px" }} roundedCircle /> :
<Image src={selectedImg} style={{ width: "300px", height: "300px" }} roundedCircle />}
</Row>
<Row className='ml-3 mt-3 justify-content-center'>
<Form className="d-flex">
......
......@@ -2,13 +2,14 @@ import Room from "../models/Room.js"
import { customAlphabet } from 'nanoid'
import isLength from 'validator/lib/isLength.js'
import Chat from "../models/Chat.js"
import EntryLog from "../models/EntryLog.js"
const nanoid = customAlphabet('1234567890abcdef', 10)
const makeRoom = async (req, res) => {
console.log(req.body)
// console.log(req.body)
const { roomName, interest, isOpen, member } = req.body;
console.log('콘솔확인', roomName, interest, isOpen, member)
// console.log('콘솔확인', roomName, interest, isOpen, member)
const roomId = nanoid()
const room = await Room.findOne({ roomId })
while (room) {
......@@ -29,7 +30,7 @@ const makeRoom = async (req, res) => {
isOpen,
member,
}).save()
console.log(newRoom)
// console.log(newRoom)
res.json(newRoom)
} catch (error) {
console.log(error)
......@@ -57,11 +58,11 @@ const getOpenList = async (req, res) => {
const getRoomName = async (req, res) => {
const roomId = req.query.roomCode
console.log('getRoomName', req.query.roomCode)
// console.log('getRoomName', req.query.roomCode)
try {
let roominfo = await Room.findOne({ roomId: roomId }).select('roomName')
console.log(roominfo.roomName)
// console.log(roominfo.roomName)
return res.json(roominfo.roomName)
} catch (error) {
res.status(500).send('리스트 불러오기를 실패하였습니다!')
......@@ -70,14 +71,14 @@ const getRoomName = async (req, res) => {
const changemember = async (req, res) => {
const { userId, roomId } = req.body
console.log(roomId)
// console.log(roomId)
let room = await Room.findOne({ roomId: roomId }).select('member')
const isPresent = room.member.indexOf(userId)
try {
if (isPresent < 0) {
const memberId = room.member.push(userId)
await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
console.log('room.member 업데이트 완료')
// console.log('room.member 업데이트 완료')
return res.json(true)
}
else {
......@@ -89,15 +90,15 @@ const changemember = async (req, res) => {
}
const deleteUserId = async (req, res) => {
console.log(req.body)
// console.log(req.body)
const { userId, roomId } = req.body
let room = await Room.findOne({ roomId: roomId }).select('member')
console.log('deletetest', room)
// console.log('deletetest', room)
const memIndex = room.member.indexOf(userId)
try {
room.member.splice(memIndex, 1)
await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
console.log(`${roomId}${userId}삭제완료`)
// console.log(`${roomId}방 ${userId}삭제완료`)
return res.json(true)
} catch (error) {
res.status(500).send('멤버 업데이트 실패')
......@@ -106,52 +107,43 @@ const deleteUserId = async (req, res) => {
const roomInf = async (req, res) => {
try {
console.log(req.query.roomId)
let roomInf = await Room.find({ roomId: req.query.roomId })
console.log('room_member로 정보 가져오기:', roomInf)
return res.json(roomInf)
} catch (error) {
alert('올바르지 못한 접근입니다.')
}
}
const unreadMessage = async (req, res) => {
let leaveInfo = req.query.leaveInfo
const roomId = req.query.roomId
let leaveTime = ''
console.log('서버에서 초기 leaveInfo',leaveInfo)
for (let i = 1; i < leaveInfo.length; i++) { //일단 형식좀 맞추고
leaveInfo[i] = JSON.parse(leaveInfo[i])
}
//findOne으로 해보자
for (let i = 1; i <= leaveInfo.length - 1; i++) { //그 방의 id와 나간기록의 방과 일치하는지 확인하고
if (leaveInfo[i].roomName === roomId) {
leaveTime = leaveInfo[i].leaveTime //그 방에서 나간 시간을 찾아옴
break;
const unreadMessage = async (req, res) => {
const nowTime = new Date().toISOString()
let leaveInfo = req.query
try {
for (const key in Object.keys(leaveInfo)) {
leaveInfo[key] = JSON.parse(leaveInfo[key]) //형식좀 제대로 맞춰주고
}
}
const room_id = await Room.find({ roomId: roomId }).select('_id') //id로 _id를 찾아와서
let unreadMsg = await Chat.find({ room: room_id }).select('createdAt') //그 방의 메세지와 전송시간을 가져옴
let count = 0
//mongoose 시간비교 방법이 있음 (gte...)
for (let i = 0; i <= unreadMsg.length - 1; i++) {
const dbtime = Date.parse(unreadMsg[i].createdAt)
const parsedleaveTime = Date.parse(leaveTime)
if (parsedleaveTime < dbtime) { //시간 비교를하고 이후에 온 메세지의 개수를 count함
console.log('이번째부터 나중에온 메세지', i)
count += 1
let countArr = []
for (const key in Object.keys(leaveInfo)) {
const room = await Room.findOne({ roomId: leaveInfo[key].roomCode }) //들어온 방 코드로 그 방의 정보 찾아옴
const entrylog = await EntryLog.findOne({ userId: leaveInfo[key].userId, room: room._id }) //그 방에서 나간시간 가져옴
if (entrylog) {
if (leaveInfo[key].now) { //보는중이면 현재시간과 비교. 즉, 없음
const count = await Chat.find({ room: room._id, createdAt: { $gte: nowTime } }) //채팅 전체에서 그 방의 채팅중 떠난시간 이후의 것들을 가져옴
countArr.push({ roomCode: room.roomId, unreadcount: count.length })
} else {
const count = await Chat.find({ room: room._id, createdAt: { $gte: entrylog.updatedAt } }) //채팅 전체에서 그 방의 채팅중 떠난시간 이후의 것들을 가져옴
countArr.push({ roomCode: room.roomId, unreadcount: count.length })
}
} else {
countArr.push(0)
}
}
res.json(countArr)
} catch (error) {
res.send(error)
}
res.json(count)
}
const dbChat = async (req, res) => {
const roomId = req.query.roomId
const room_id = await Room.find({ roomId: roomId }).select('_id')
let chatlist = await Chat.find({ room: room_id }).select('message')
res.json(chatlist)
}
export default { makeRoom, getClosedList, getOpenList, getRoomName, changemember, roomInf, unreadMessage, dbChat, deleteUserId }
export default { makeRoom, getClosedList, getOpenList, getRoomName, changemember, roomInf, unreadMessage, deleteUserId }
import Room from "../models/Room.js"
import Chat from "../models/Chat.js";
import User from "../models/User.js";
import EntryLog from "../models/EntryLog.js";
const roomEnter = async (req, res) => {
const roomId = req.body.enterCode
......@@ -33,5 +34,53 @@ const getChatInfo = async (req, res) => {
}
//그사람의 그방에서의 기록이 있는지 확인
const checklog = async (req, res) => {
console.log('@@@@@서버에서 체크 로그')
const { userId, roomCode } = req.query
const roomId = await Room.findOne({ roomId: roomCode })
try {
const entrylog = await EntryLog.findOne({ userId: userId, room: roomId })
res.json(Boolean(entrylog))
} catch (error) {
res.json(false)
}
}
//출입기록 업로드
const uploadlog = async (req, res) => {
console.log('@@@@@서버에서 업로드 로그')
const { userId, leaveTime, roomCode } = req.body
const user = await User.findOne({ _id: userId }) // 받아온 _id로 그 유저의 정보 가져옴
const room = await Room.findOne({ roomId: roomCode }) // 받아온 roomCode로 그 방의 정보 가져옴
try {
const entrylog = await new EntryLog({
userId: user._id,
room: room._id,
leaveTime: leaveTime,
}).save()
res.json(entrylog)
} catch (error) {
console.log(error)
res.send(500).send('출입시간이 기록되지 않았습니다.')
}
}
//출입기록 수정
const updatelog = async (req, res) => {
console.log('@@@@@서버에서 업데이트 로그')
const { userId, leaveTime, roomCode } = req.body
console.log('@@@@@', leaveTime, userId, roomCode)
const room = await Room.findOne({ roomId: roomCode })
try {
await EntryLog.updateOne({ userId: userId, room: room._id }, { leaveTime: leaveTime }) //항상 id와 room이 둘다 맞는걸 수정해야함 !
res.send('finished')
} catch (error) {
console.log(error)
res.send(500).send('출입시간 업데이트 실패')
}
}
export default { roomEnter, getChatInfo }
\ No newline at end of file
export default { roomEnter, getChatInfo, checklog, uploadlog, updatelog }
\ No newline at end of file
import mongoose from 'mongoose'
const { String } = mongoose.Schema.Types
const EntryLogSchema = new mongoose.Schema({
userId: {
type: mongoose.ObjectId,
required: true,
ref: 'User',
},
room: {
type: mongoose.ObjectId,
required: true,
ref: 'Room',
},
leaveTime: {
type: String,
required: true,
}
}, {
timestamps: true
})
export default mongoose.models.EntryLog || mongoose.model('EntryLog', EntryLogSchema)
......@@ -34,9 +34,6 @@ const UserSchema = new mongoose.Schema({
type: String,
default: '3cd14b9bcb2007f324fcb82e0b566cce',
},
entrylog: {
type: Array,
}
}, {
timestamps: true
......
......@@ -22,14 +22,9 @@ router.route('/room/member')
router.route('/room/getRoomName')
.get(roomCtrl.getRoomName)
// router.route('/room/unreadMessage')
// .get(roomCtrl.unreadMessage)
router.route('/room/unreadMessage')
.get(roomCtrl.unreadMessage)
router.route('/room/dbChat')
.get(roomCtrl.dbChat)
router.route('/room/deleteMem')
.put(roomCtrl.deleteUserId)
......
......@@ -9,5 +9,10 @@ router.route('/room/enterRoom')
router.route('/room/getChatInfo')
.get(roomEnterCtrl.getChatInfo)
router.route('/room/entrylog')
.get(roomEnterCtrl.checklog)
.post(roomEnterCtrl.uploadlog)
.put(roomEnterCtrl.updatelog)
export default router
\ No newline at end of file
......@@ -23,21 +23,21 @@ io.on("connection", (socket) => { // 기본 연결
console.log("socket connect ok", socket.id)
socket.on('joinRoom', (data) => { // joinRoom을 클라이언트가 emit했을 때
console.log('join_data확인', data)
// console.log('join_data확인', data)
let roomInfo = data;
socket.join(roomInfo); //클라이언트에서 data에 적힌 room으로 참여시킴
});
socket.on('closeRoom', (data) => {
console.log('close_data확인', data)
// console.log('close_data확인', data)
let roomInfo = data;
socket.leave(roomInfo); //클라이언트에서 data에 적힌 room정보를 브로드캐스팅 받지 않는다.
});
socket.on('chat', async (data) => {
console.log('roomname확인', data)
// console.log('roomname확인', data)
const room = await Room.findOne({ roomId: data.roomInfo })
console.log('room이 떴나', room)
// console.log('room이 떴나', room)
const chat = await new Chat({
room: room._id,
......@@ -45,10 +45,10 @@ io.on("connection", (socket) => { // 기본 연결
message: data.sendInfo.msg,
profileimg: data.sendInfo.img
}).save()
console.log('resChat확인', chat)
// console.log('resChat확인', chat)
socket.broadcast.to(data.roomInfo).emit('sendedMSG', data.sendInfo); // sender 제외 특정 방으로
socket.broadcast.emit('checking', data.sendInfo) // 메세지를 어딘가에서 보냈다는 신호
});
socket.on('disconnect', () => {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment