Commit 216a1640 authored by JeongYeonwoo's avatar JeongYeonwoo
Browse files

socket해서 푸쉬한것 입니다.

parent 28a309f0
...@@ -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 from 'react';
import { Form, Button } from 'react-bootstrap'; import { Form, Button, Row } from 'react-bootstrap';
function Chat(props) { function Chat(props) {
function handleChange(e) {
e.preventDefault()
props.setInner(e.target.value)
console.log(e.target.value)
}
function sendMsgCH(e) {
props.sendMsg(e)
}
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" }}>
<Button variant="light" onClick={props.handleChatc} >{`<`}</Button> <Button variant="light" onClick={props.handleChatc} >{`<`}</Button>
<h2>현재 {props.roomName} 입니다.</h2>
{ props.chatmsg.map((value, index) => (
<Row key={index} className='ml-3'>
{props.roomName}에서 보낸 메세지 : {value}
</Row>
))}
<Form onSubmit={sendMsgCH}>
<Form.Control name='msg' type='text' onChange={handleChange} />
<Button variant="primary" type="submit">전송</Button>
</Form>
<Form> <Form>
<Form.Group> <Form.Group>
<Form.Control type="text" /> <Form.Control type="text" />
......
import React, { useState } from 'react' import React, { useState } from 'react'
import { ListGroup } from 'react-bootstrap'; import { ListGroup, Row, Col } 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) {
const roomName = e.target.name
props.enterChatroom(roomName) // 각각의 room으로 들어가도록 설정해야 함
props.setRoomName(roomName)
props.clearChat()
}
return ( return (
<div> <div>
{list.map((list, index) => <Row>
<ListGroup key={index}> {list.map((list, index) =>
<ListGroup.Item action> <ListGroup key={index}>
<h2>{list.room}</h2> <ListGroup.Item action onClick={enterChatroomCH} name={list.room}>
</ListGroup.Item> {list.room}
</ListGroup> </ListGroup.Item>
)} </ListGroup>
)}
</Row>
<Col>
</Col>
</div> </div>
) )
} }
......
import React, { useState } from 'react'; import React, { useState, useEffect } from 'react';
import { Row, Col, Modal, Button, Navbar, Nav } from 'react-bootstrap'; import { Row, Col, Modal, Button, Navbar, Nav } from 'react-bootstrap';
import Tabs from 'react-bootstrap/Tabs'; import Tabs from 'react-bootstrap/Tabs';
import Tab from 'react-bootstrap/Tab'; import Tab from 'react-bootstrap/Tab';
...@@ -7,12 +7,14 @@ import OpenList from '../Components/OpenList'; ...@@ -7,12 +7,14 @@ import OpenList from '../Components/OpenList';
import Chat from '../Components/Chat'; import Chat from '../Components/Chat';
import Menu from '../Components/Menu'; import Menu from '../Components/Menu';
// import styled from 'styled-components'; // import styled from 'styled-components';
import { io } from "socket.io-client"; //모듈 가져오기
// const List = styled.div` // const List = styled.div`
// background: #FFFAFA; // background: #FFFAFA;
// ` // `
const userName = "정연우"; const userName = "정연우";
const socket = io();
function Home() { function Home() {
...@@ -25,6 +27,51 @@ function Home() { ...@@ -25,6 +27,51 @@ function Home() {
const handleChatc = () => setChat(false); const handleChatc = () => setChat(false);
// variant="pills" // variant="pills"
///////////////////////////////////////////////////////////////
const [inner, setInner] = useState([''])
console.log('sendMsg2222', inner)
const [chatmsg, setChatmsg] = useState([inner])
const [roomName, setRoomName] = useState('dd') //방 선택이 방1을 눌럿다 방2를 누르면 전체로 전송됨
function enterChatroom(roomName) { //방 입장하기
socket.emit('joinRoom', roomName)
console.log(`joinRoom : ${roomName} 입장`)
}
const sendMsg = (e) => {
e.preventDefault()
console.log('sendMsg', inner)
console.log(roomName)
socket.emit("chat", {
roomName: roomName,
msg: inner
});
}
function clearChat() {
setChatmsg([])
}
useEffect(() => {
console.log('useeffect1')
socket.on('broadcast', (msg) => {
console.log('msg', msg)
console.log('inner :', inner)
setChat([...chatmsg, msg])
})
console.log('useeffect2', chat)
}, [chatmsg])
//////////////////////////////////////////////////////////
return ( return (
<> <>
<Menu /> <Menu />
...@@ -32,7 +79,7 @@ function Home() { ...@@ -32,7 +79,7 @@ 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} clearChat={clearChat} />
</Tab> </Tab>
<Tab eventKey="open" title="공개방" > <Tab eventKey="open" title="공개방" >
<OpenList /> <OpenList />
...@@ -40,7 +87,7 @@ function Home() { ...@@ -40,7 +87,7 @@ function Home() {
</Tabs> </Tabs>
</Col> </Col>
<Col style={{ padding: "0" }}> <Col style={{ padding: "0" }}>
{chat ? <Chat handleChatc={handleChatc} /> : null} {chat ? <Chat handleChatc={handleChatc} sendMsg={sendMsg} setInner={setInner} chatmsg={chatmsg} roomName={roomName} /> : null}
<Button variant="primary" onClick={handleShow} style={{ position: "fixed", bottom: "10px", right: "10px" }} > <Button variant="primary" onClick={handleShow} style={{ position: "fixed", bottom: "10px", right: "10px" }} >
생성 생성
......
...@@ -6,10 +6,14 @@ ...@@ -6,10 +6,14 @@
"type": "module", "type": "module",
"dependencies": { "dependencies": {
"bcryptjs": "^2.4.3", "bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1", "express": "^4.17.1",
"jsonwebtoken": "^8.5.1", "jsonwebtoken": "^8.5.1",
"mongoose": "^5.11.9", "mongoose": "^5.11.9",
"nodemon": "^2.0.6", "nodemon": "^2.0.6",
"require-node": "^2.0.8",
"socket.io": "^3.0.5",
"validator": "^13.5.2" "validator": "^13.5.2"
}, },
"devDependencies": {}, "devDependencies": {},
......
...@@ -4,12 +4,50 @@ import userRouter from './routes/user.routes.js' ...@@ -4,12 +4,50 @@ import userRouter from './routes/user.routes.js'
import authRouter from './routes/auth.routes.js' import authRouter from './routes/auth.routes.js'
import profileRouter from './routes/profile.routes.js' import profileRouter from './routes/profile.routes.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()) const server = http.createServer(app);
const io = new Server(server)
io.on("connection", (socket) => { // 기본 연결
console.log("socket connect ok", socket.id)
socket.on('joinRoom', (data) => { // joinRoom을 클라이언트가 emit했을 때
let roomName = data;
console.log(roomName, "방 입장")
socket.join(roomName); //클라이언트에서 data에 적힌 room으로 참여시킴
});
socket.on('chat', (data) => {
console.log(`chat실행 :`, data.roomName, data.msg)
io.to(data.roomName).emit('broadcast', data.msg); //roomName에 존재하는 모든 소켓들에게
})
socket.on('disconnect', () => {
console.log('disconnected from server id=', socket.id)
})
});
// app.use(express.json())
//이부분을 body 파싱함 //이부분을 body 파싱함
app.use(bodyParser.json());
// app.use(cors());
// app.use('/', indexRouter);
//express가 req.body라는곳을 자동으로만들어서 json형식으로 보낸것을 객체형식으로 넣음 //express가 req.body라는곳을 자동으로만들어서 json형식으로 보낸것을 객체형식으로 넣음
//이부분 다음부터는 req.body라는 부분을 실행할 수 있음 //이부분 다음부터는 req.body라는 부분을 실행할 수 있음
...@@ -19,9 +57,16 @@ app.use(profileRouter) ...@@ -19,9 +57,16 @@ app.use(profileRouter)
//userRouter로 이동 //userRouter로 이동
app.get('/', (req, res) => { app.get('/', (req, res) => {
res.send('Hello World. 안녕하세요') res.send('Hello World. 안녕하세요')
}) })
app.listen(3030, () => { app.listen(3030, () => {
console.log('Listening on port 3030') console.log('Listening on port 3030')
}) })
/////////////////////////////////////////////////////////
// export default server
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