Commit 1b0c048c authored by Soo Hyun Kim's avatar Soo Hyun Kim
Browse files

soo0115

parent eda45ede
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
"react-dom": "^17.0.1", "react-dom": "^17.0.1",
"react-router-dom": "^5.2.0", "react-router-dom": "^5.2.0",
"react-scripts": "4.0.1", "react-scripts": "4.0.1",
"socket.io-client": "^3.0.5",
"web-vitals": "^0.2.4" "web-vitals": "^0.2.4"
}, },
"scripts": { "scripts": {
......
import React from 'react'; import React, { useState, useEffect } from 'react';
import { Form, Button } from 'react-bootstrap'; import { Form, Button, Row } from 'react-bootstrap';
function Chat(props) { function Chat(props) {
const [inner, setInner] = useState([''])
const [chat, setChat] = useState([inner]) //object로 key는 보낸사람 value는 메세지
function handleChange(e) {
e.preventDefault()
setInner(e.target.value)
console.log(e.target.value)
}
function sendMsgCH(e) {
e.preventDefault()
props.setSingleChat(inner)
props.sendMsg(e)
setInner('')
}
useEffect(() => {
setChat([...chat, props.singleChat])
}, [props.singleChat])
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>
{ chat.map((value, index) => (
<Row key={index} className='ml-3'>
{props.roomName}에서 보낸 메세지 : {value}
</Row>
))}
<Button variant="light" onClick={props.handleChatc} >{`<`}</Button> <Button variant="light" onClick={props.handleChatc} >{`<`}</Button>
<Form> <Form onSubmit={sendMsgCH}>
<Form.Group> <Form.Group>
<Form.Control type="text" /> <Form.Control name='chat' type="text" value={inner} onChange={handleChange} />
</Form.Group> </Form.Group>
<Button variant="primary" type="submit"> <Button variant="primary" type="submit">
전송 전송
......
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 } from 'react' import React, { useState } from 'react'
import { ListGroup } from 'react-bootstrap'; import { ListGroup } from 'react-bootstrap';
function ClosedList() { function ClosedList(props) {
const [list, setList] = useState([ const [list, setList] = useState([
{ room: '테스트 방1', memnum: 5, admin: '가영' }, { room: '테스트 방1', memnum: 5, admin: '가영' },
{ room: '테스트 방2', memnum: 4, admin: '수현' }] { room: '테스트 방2', memnum: 4, admin: '수현' }]
); );
function enterChatroomCH(e) {
console.log(e.target.name)
console.log(e.target)
const roomName = e.target.name
props.enterChatroom(roomName) // 각각의 room으로 들어가도록 설정해야 함
props.setRoomName(roomName)
// props.clearChat()
}
return ( return (
<div> <div>
{list.map((list, index) => {list.map((item, index) =>
<ListGroup key={index}> <ListGroup key={index}>
<ListGroup.Item action> <ListGroup.Item action onClick={enterChatroomCH} id='diddkdk' name={item.room}>
<h2>{list.room}</h2> {item.room}
</ListGroup.Item> </ListGroup.Item>
</ListGroup> </ListGroup>
)} )}
......
import React, { useState } from 'react' import React, { useState } from 'react'
import { ListGroup } from 'react-bootstrap'; import { ListGroup } from 'react-bootstrap';
function OpenList() { function OpenList(props) {
const [list, setList] = useState([ const [list, setList] = useState([
{ room: '테스트 방3', memnum: 7, admin: '가영2' }, { room: '테스트 방3', memnum: 7, admin: '가영2' },
{ room: '테스트 방4', memnum: 2, admin: '수현2' }] { room: '테스트 방4', memnum: 2, admin: '수현2' }]
); );
function enterChatroomCH(e) {
const roomName = e.target.name
props.enterChatroom(roomName) // 각각의 room으로 들어가도록 설정해야 함
props.setRoomName(roomName)
// props.clearChat()
}
return ( return (
<div> <div>
{list.map((list, index) => {list.map((list, index) =>
<ListGroup key={index}> <ListGroup key={index}>
<ListGroup.Item action> <ListGroup.Item action onClick={enterChatroomCH} name={list.room}>
<h2>{list.room}</h2> <h2>{list.room}</h2>
</ListGroup.Item> </ListGroup.Item>
</ListGroup> </ListGroup>
......
...@@ -5,15 +5,18 @@ import Tabs from 'react-bootstrap/Tabs'; ...@@ -5,15 +5,18 @@ import Tabs from 'react-bootstrap/Tabs';
import Tab from 'react-bootstrap/Tab'; import Tab from 'react-bootstrap/Tab';
import ClosedList from '../Components/ClosedList'; import ClosedList from '../Components/ClosedList';
import OpenList from '../Components/OpenList'; import OpenList from '../Components/OpenList';
import Chat from '../Components/Chat';
import Menu from '../Components/Menu'; import Menu from '../Components/Menu';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
import { io } from "socket.io-client"; //모듈 가져오기
import Chat from "../Components/Chat";
// import styled from 'styled-components'; // import styled from 'styled-components';
// const List = styled.div` // const List = styled.div`
// background: #FFFAFA; // background: #FFFAFA;
// ` // `
const socket = io();
const INIT_CHATR = { const INIT_CHATR = {
name: '', name: '',
interest: '', interest: '',
...@@ -24,11 +27,13 @@ function Home() { ...@@ -24,11 +27,13 @@ function Home() {
const [show, setShow] = useState(false); const [show, setShow] = useState(false);
const [show2, setShow2] = useState(false); const [show2, setShow2] = useState(false);
const [chat, setChat] = useState(false); const [chat, setChat] = useState(false);
// const [checkedI, setCheckedI] = useState(false);
const [chatR, setChatR] = useState(INIT_CHATR); const [chatR, setChatR] = useState(INIT_CHATR);
const [disabled, setDisabled] = useState(true); const [disabled, setDisabled] = useState(true);
const [error, setError] = useState(''); const [error, setError] = useState('');
const [singleChat, setSingleChat] = useState('')
const [roomName, setRoomName] = useState('')
const handleClose = () => setShow(false); const handleClose = () => setShow(false);
const handleShow = () => setShow(true); const handleShow = () => setShow(true);
const handleChato = () => setChat(true); const handleChato = () => setChat(true);
...@@ -51,14 +56,6 @@ function Home() { ...@@ -51,14 +56,6 @@ function Home() {
event.preventDefault() event.preventDefault()
try { try {
setError('') setError('')
// const response = await fetch('chat/makeChat', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify(chatR)
// })
//const data = await response.json()
const response = await axios.post('chat/makeChat', chatR) const response = await axios.post('chat/makeChat', chatR)
setChatR(INIT_CHATR) setChatR(INIT_CHATR)
} catch (error){ } catch (error){
...@@ -66,6 +63,28 @@ function Home() { ...@@ -66,6 +63,28 @@ function Home() {
} }
} }
//SOCKET 관련 시작
function enterChatroom(rName) { //방 입장하기
socket.emit('joinRoom', rName)
console.log(`joinRoom : ${rName} 입장`)
}
const sendMsg = (e) => {
e.preventDefault()
}
useEffect(() => {
socket.emit("chat", {
roomName: roomName,
msg: singleChat
})
socket.on('broadcast', (msg) => {
console.log(msg)
setSingleChat(msg)
})
}, [singleChat])
return ( return (
<> <>
<Menu /> <Menu />
...@@ -73,15 +92,15 @@ function Home() { ...@@ -73,15 +92,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 /> <ClosedList enterChatroom={enterChatroom} setRoomName={setRoomName}/>
</Tab> </Tab>
<Tab eventKey="open" title="공개방" > <Tab eventKey="open" title="공개방" >
<OpenList /> <OpenList enterChatroom={enterChatroom} setRoomName={setRoomName}/>
</Tab> </Tab>
</Tabs> </Tabs>
</Col> </Col>
<Col style={{ padding: "0" }}> <Col style={{ padding: "0" }}>
{chat ? <Chat handleChatc={handleChatc} /> : null} {chat ? <Chat handleChatc={handleChatc} sendMsg={sendMsg} singleChat={singleChat} setSingleChat={setSingleChat} roomName={roomName}/> : null}
<div style={{ position: "fixed", bottom: "20px", right: "30px" }}> <div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
<Button variant="primary" onClick={handleShow} size="lg" block> <Button variant="primary" onClick={handleShow} size="lg" block>
......
...@@ -16,10 +16,13 @@ ...@@ -16,10 +16,13 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1", "express": "^4.17.1",
"mongoose": "^5.11.9", "mongoose": "^5.11.9",
"nanoid": "^3.1.20", "nanoid": "^3.1.20",
"nodemon": "^2.0.6", "nodemon": "^2.0.6",
"socket.io": "^3.0.5",
"validator": "^13.5.2" "validator": "^13.5.2"
} }
} }
import express from 'express' import express from 'express'
import connectDb from './utils/connectDb.js' import connectDb from './utils/connectDb.js'
import chatRouter from './routes/chat.routers.js' import chatRouter from './routes/chat.routers.js'
import cors from "cors"
import bodyParser from "body-parser"
import http from 'http'
import { Server } from 'socket.io'
connectDb() connectDb()
const app = express() const app = express()
app.use(express.json()) app.use(express.json())
//이부분을 body 파싱함
//express가 req.body라는곳을 자동으로만들어서 json형식으로 보낸것을 객체형식으로 넣음
//이부분 다음부터는 req.body라는 부분을 실행할 수 있음
app.use(chatRouter) app.use(chatRouter)
//userRouter로 이동
// app.post('/makeChat', (req, res) => { const server = http.createServer(app);
// app.use(chatRouter)
// }) const io = new Server(server);
// const port = process.env.PORT || 3001; // 3001 수정해야하나?
app.use(bodyParser.json());
app.use(cors());
// app.use('/', indexRouter);
// app.get('/', (req, res) => { io.on("connection", (socket) => { // 기본 연결
// res.send('Hello World. 안녕하세요') console.log("socket connect ok", socket.id)
// })
app.listen(3030, () => { socket.on('joinRoom', (data)=>{ // joinRoom을 클라이언트가 emit했을 때
let roomName=data;
socket.join(roomName); //클라이언트에서 data에 적힌 room으로 참여시킴
});
socket.on('chat', (data)=>{
io.to(data.roomName).emit('broadcast',data.msg); //roomName에 존재하는 모든 소켓들에게
})
socket.on('disconnect', () => {
console.log('disconnected from server id=', socket.id)
})
});
server.listen(3030, () => {
console.log('Listening on port 3030') console.log('Listening on port 3030')
}) })
// server.listen(port, () => { console.log(`Listening on port ${port}`) });
export default server
// module.exports = server;
\ No newline at end of file
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