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

채팅방 분리, 브로드캐스팅, 불필요한거 삭제

parent 0a02c1c5
node_modules node_modules
package-lock.json package-lock.json
uploads
\ No newline at end of file
...@@ -32,12 +32,12 @@ function Chat(props) { ...@@ -32,12 +32,12 @@ function Chat(props) {
return ( return (
<div className="chat" id="chat" style={{ border: "2px solid", height: "300%", margin: "1%", borderColor: "#BDBDBD" }}> <div className="chat" id="chat" style={{ border: "2px solid", height: "300%", margin: "1%", borderColor: "#BDBDBD" }}>
<h2>현재 {props.roomName} 입니다.</h2> <h2>해당 방에 대한 참여코드는 {props.roomCode} 입니다.</h2>
{ chat.map((value, index) => { { chat.map((value, index) => {
if (!(value=='')) { if (!(value=='')) {
// console.log(`value=${value}=`) // console.log(`value=${value}=`)
return <Row key={index} className='ml-3'> return <Row key={index} className='ml-3'>
{props.roomName}에서 {defaultname}님이 보낸 메세지 : {value} {defaultname}님이 보낸 메세지 : {value}
</Row> </Row>
} else { } else {
return null return null
......
import React, { useState } from 'react';
import { Form, Row, Col, Button } from 'react-bootstrap'
function ChatForm(props) {
const INIT_SAYING = ''
const [saying, setSaying] = useState(INIT_SAYING);
function handleChange(event) {
const { name, value } = event.target
setSaying(value)
console.log(saying)
}
function handleSubmit(event) {
event.preventDefault()
// const response = await axios.post('chat/makeChat', chatR)
props.setSingleChat()
setSaying(INIT_SAYING)
}
return (
<Form onSubmit={handleSubmit}>
<Row>
<Col>
<Form.Group>
<Form.Control name='chat' type='text' onChange={handleChange}>chat</Form.Control>
</Form.Group>
</Col>
<Col>
<Form.Group>
<Button type="submit">send</Button>
</Form.Group>
</Col>
</Row>
</Form>
)
}
export default ChatForm
\ No newline at end of file
import React, { useState, useEffect } from 'react' import React, { useState, useEffect } from 'react'
import { ListGroup, Row, Col } from 'react-bootstrap'; import { ListGroup } from 'react-bootstrap';
import axios from 'axios' import axios from 'axios'
function ClosedList(props) { function ClosedList(props) {
...@@ -10,32 +10,24 @@ function ClosedList(props) { ...@@ -10,32 +10,24 @@ function ClosedList(props) {
getClosedList(); getClosedList();
}, []); }, []);
const userId = sessionStorage.getItem('userId');
async function getClosedList() { async function getClosedList() {
const userid = sessionStorage.getItem('userId') const userid = sessionStorage.getItem('userId')
console.log('id가져오기', userid)
let res = await axios.get('/room/closedlist', { params: { '_id': userid } }) let res = await axios.get('/room/closedlist', { params: { '_id': userid } })
console.log('가져온거', res)
setList(res.data) setList(res.data)
} }
function enterChatRoomCH(e) { function enterChatRoomCH(e) {
console.log(e.target.name) const roomCode = e.target.name
console.log(e.target) props.enterChatRoom(roomCode)
const roomName = e.target.name props.setRoomCode(roomCode)
props.enterChatroom(roomName) // 각각의 room으로 들어가도록 설정해야 함
props.setRoomName(roomName)
} }
//user.hasOwnProperty('이름');
return ( return (
<div> <div>
{list.map((item, index) => {list.map((item, index) =>
<ListGroup key={index}> <ListGroup key={index}>
<ListGroup.Item action onClick={enterChatRoomCH} name={item.roomName}> <ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId}>
{item.roomName} {item.roomName}
</ListGroup.Item> </ListGroup.Item>
</ListGroup> </ListGroup>
......
import React, { useState } from 'react' import React, { useState } from 'react'
import axios from 'axios'; import axios from 'axios';
import { Row, Col, Modal, Button, Form, Alert } from 'react-bootstrap'; import { Row, Col, Modal, Button, Form } from 'react-bootstrap';
import catchErrors from '../utils/catchErrors' import catchErrors from '../utils/catchErrors'
......
...@@ -11,15 +11,14 @@ function OpenList(props) { ...@@ -11,15 +11,14 @@ function OpenList(props) {
async function getOpenList() { async function getOpenList() {
let res = await axios.get('/room/openlist') let res = await axios.get('/room/openlist')
console.log('가져온거o', res)
setOpenlist(res.data) setOpenlist(res.data)
} }
function enterChatRoomCH(e) { function enterChatRoomCH(e) {
const roomName = e.target.name const roomCode = e.target.name
props.enterChatroom(roomName) // 각각의 room으로 들어가도록 설정해야 함 props.enterChatRoom(roomCode) // 각각의 room으로 들어가도록 설정해야 함
props.setRoomName(roomName) props.setRoomCode(roomCode)
// props.clearChat() // props.clearChat()
} }
...@@ -27,7 +26,7 @@ function OpenList(props) { ...@@ -27,7 +26,7 @@ function OpenList(props) {
<div> <div>
{openlist.map((item, index) => {openlist.map((item, index) =>
<ListGroup key={index}> <ListGroup key={index}>
<ListGroup.Item action onClick={enterChatRoomCH} name={item.roomName}> <ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId}>
{item.roomName} {item.roomName}
</ListGroup.Item> </ListGroup.Item>
</ListGroup> </ListGroup>
......
//로그인 한 사람만 route로 이동할 수 있도록 함
import React from 'react' import React from 'react'
import { Redirect, Route } from 'react-router-dom' import { Redirect, Route } from 'react-router-dom'
import { isAuthenticated } from '../utils/auth' import { isAuthenticated } from '../utils/auth'
function PrivateRoute({path, children}) { function PrivateRoute({path, children}) {
if (isAuthenticated()) { if (isAuthenticated()) {
//로그인이 됬을 시 정상적으로 작동
return ( return (
<Route path={path}> <Route path={path}>
{children} {children}
</Route> </Route>
) )
} else { } else {
//로그인이 되지 않았을 시 로그인페이지로 이동
return ( return (
<Redirect to='./login' /> <Redirect to='./login' />
) )
......
...@@ -20,11 +20,9 @@ function Home() { ...@@ -20,11 +20,9 @@ function Home() {
//소켓 //소켓
const [singleChat, setSingleChat] = useState('') const [singleChat, setSingleChat] = useState('')
const [recievedMsg, setRecievedMsg] = useState('') const [recievedMsg, setRecievedMsg] = useState('')
const [roomName, setRoomName] = useState('')
const [roomCode, setRoomCode] = useState('') const [roomCode, setRoomCode] = useState('')
//방참가 //방참가
const [roomId, setRoomId] = useState('')
const handleCloseModal = () => setShowModal(false); const handleCloseModal = () => setShowModal(false);
const handleShowModal = () => setShowModal(true); const handleShowModal = () => setShowModal(true);
...@@ -36,7 +34,7 @@ function Home() { ...@@ -36,7 +34,7 @@ function Home() {
//SOCKET 관련 시작 //SOCKET 관련 시작
function enterChatroom(rName) { //방 입장하기 function enterChatRoom(rName) { //방 입장하기
socket.emit('joinRoom', rName) socket.emit('joinRoom', rName)
console.log(`joinRoom : ${rName} 입장`) console.log(`joinRoom : ${rName} 입장`)
} }
...@@ -48,7 +46,7 @@ function Home() { ...@@ -48,7 +46,7 @@ function Home() {
useEffect(() => { useEffect(() => {
if (!(singleChat == '')) { if (!(singleChat == '')) {
socket.emit("chat", { socket.emit("chat", {
roomName: roomCode, roomInfo: roomCode,
msg: singleChat msg: singleChat
}) })
setSingleChat(['']) setSingleChat([''])
...@@ -70,15 +68,15 @@ function Home() { ...@@ -70,15 +68,15 @@ function Home() {
<Col className="list" md={5}> <Col className="list" md={5}>
<Tabs defaultActiveKey="closed" id="uncontrolled-tab-example"> <Tabs defaultActiveKey="closed" id="uncontrolled-tab-example">
<Tab eventKey="closed" title="내 채팅" onClick={handleChato} > <Tab eventKey="closed" title="내 채팅" onClick={handleChato} >
<ClosedList enterChatRoom={enterChatRoom} setRoomName={setRoomName}/> <ClosedList enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} />
</Tab> </Tab>
<Tab eventKey="open" title="공개방" > <Tab eventKey="open" title="공개방" onClick={handleChato}>
<OpenList enterChatRoom={enterChatRoom} setRoomName={setRoomName}/> <OpenList enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} />
</Tab> </Tab>
</Tabs> </Tabs>
</Col> </Col>
<Col style={{ padding: "0" }}> <Col style={{ padding: "0" }}>
{chat ? <Chat handleChatc={handleChatc} sendMsg={sendMsg} singleChat={singleChat} recievedMsg={recievedMsg} setSingleChat={setSingleChat} roomName={roomName} /> : null} {chat ? <Chat handleChatc={handleChatc} sendMsg={sendMsg} singleChat={singleChat} recievedMsg={recievedMsg} setSingleChat={setSingleChat} roomCode={roomCode} /> : null}
<div style={{ position: "fixed", bottom: "20px", right: "30px" }}> <div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
<Button variant="primary" onClick={handleShowModal} size="lg" block> <Button variant="primary" onClick={handleShowModal} size="lg" block>
...@@ -92,7 +90,7 @@ function Home() { ...@@ -92,7 +90,7 @@ function Home() {
</Col> </Col>
</Row> </Row>
<RoomMake showModal={showModal} handleCloseModal={handleCloseModal} /> <RoomMake showModal={showModal} handleCloseModal={handleCloseModal} />
<EnterRoom showEnter={showEnter} enterChatRoom={enterChatroom} handleCloseEnter={handleCloseEnter} /> <EnterRoom showEnter={showEnter} enterChatRoom={enterChatRoom} handleCloseEnter={handleCloseEnter} />
</> </>
); );
} }
......
import React, { useState, useEffect } from 'react' import React, { useState, useEffect } from 'react'
import Menu from '../Components/Menu'; import Menu from '../Components/Menu';
import { Image, Button, Container, Form, Row, Col, Dropdown } from 'react-bootstrap'; import { Image, Button, Container, Form, Row, Col } from 'react-bootstrap';
import { BrowserRouter as Link } from 'react-router-dom'; import { BrowserRouter as Link } from 'react-router-dom';
import axios from 'axios' import axios from 'axios'
import catchErrors from '../utils/catchErrors' import catchErrors from '../utils/catchErrors'
...@@ -76,20 +76,6 @@ function ProfilePage() { ...@@ -76,20 +76,6 @@ function ProfilePage() {
getProfile(userId) getProfile(userId)
}, [userId]) }, [userId])
// const [img, setImg] = useState('')
// function bbb(e) {
// const { name } = e.target
// let reader = new FileReader();
// reader.onload = function (e){
// console.log(e.target.result)
// // setImg(e.target.result)
// // setProfileimg
// // console.log(user,name)
// setUser({...user, [name]: e.target.result})
// };
// reader.readAsDataURL(e.target.files[0])
// )
return ( return (
<> <>
<Menu /> <Menu />
......
...@@ -2,7 +2,7 @@ import React from 'react'; ...@@ -2,7 +2,7 @@ import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css'; import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css'; import './index.css';
import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import reportWebVitals from './reportWebVitals'; import reportWebVitals from './reportWebVitals';
import SignUpPage from './Pages/SignUpPage'; import SignUpPage from './Pages/SignUpPage';
import ProfilePage from './Pages/ProfilePage'; import ProfilePage from './Pages/ProfilePage';
......
...@@ -21,16 +21,15 @@ io.on("connection", (socket) => { // 기본 연결 ...@@ -21,16 +21,15 @@ io.on("connection", (socket) => { // 기본 연결
console.log("socket connect ok", socket.id) console.log("socket connect ok", socket.id)
socket.on('joinRoom', (data)=>{ // joinRoom을 클라이언트가 emit했을 때 socket.on('joinRoom', (data)=>{ // joinRoom을 클라이언트가 emit했을 때
let roomName=data; console.log('join_data확인',data)
socket.join(roomName); //클라이언트에서 data에 적힌 room으로 참여시킴 let roomInfo=data;
socket.join(roomInfo); //클라이언트에서 data에 적힌 room으로 참여시킴
}); });
// socket.on('chat', (data)=>{
// io.to(data.roomName).emit('chat',data.msg); //roomName에 존재하는 모든 소켓들에게
// })
socket.on('chat', (data) => { socket.on('chat', (data) => {
socket.broadcast.emit('sendedMSG', data.msg ); // everyone gets it but the sender console.log('roomname확인', data)
socket.broadcast.to(data.roomInfo).emit('sendedMSG', data.msg ); // sender 제외 특정 방으로
}); });
socket.on('disconnect', () => { socket.on('disconnect', () => {
...@@ -39,8 +38,6 @@ io.on("connection", (socket) => { // 기본 연결 ...@@ -39,8 +38,6 @@ io.on("connection", (socket) => { // 기본 연결
}); });
// app.use(express.json())
//이부분을 body 파싱함
app.use(bodyParser.json()); app.use(bodyParser.json());
app.use(cors()); app.use(cors());
......
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