{"id":18577487,"url":"https://github.com/pjt3591oo/react-socket-tutorial","last_synced_at":"2026-05-17T03:35:49.634Z","repository":{"id":43566316,"uuid":"204231154","full_name":"pjt3591oo/react-socket-tutorial","owner":"pjt3591oo","description":null,"archived":false,"fork":false,"pushed_at":"2023-01-04T08:04:38.000Z","size":6429,"stargazers_count":0,"open_issues_count":26,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-10-29T18:41:58.365Z","etag":null,"topics":["docker","hooks","javascript","mount","socket"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pjt3591oo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-08-25T01:21:44.000Z","updated_at":"2021-12-25T00:40:01.000Z","dependencies_parsed_at":"2023-02-02T04:32:04.381Z","dependency_job_id":null,"html_url":"https://github.com/pjt3591oo/react-socket-tutorial","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/pjt3591oo/react-socket-tutorial","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pjt3591oo%2Freact-socket-tutorial","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pjt3591oo%2Freact-socket-tutorial/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pjt3591oo%2Freact-socket-tutorial/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pjt3591oo%2Freact-socket-tutorial/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pjt3591oo","download_url":"https://codeload.github.com/pjt3591oo/react-socket-tutorial/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pjt3591oo%2Freact-socket-tutorial/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33126502,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-16T18:38:32.183Z","status":"online","status_checked_at":"2026-05-17T02:00:05.366Z","response_time":107,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["docker","hooks","javascript","mount","socket"],"created_at":"2024-11-06T23:29:21.477Z","updated_at":"2026-05-17T03:35:49.617Z","avatar_url":"https://github.com/pjt3591oo.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# react socket tutorial\n\n* 1.start\n* 2.socket 객체생성\n* 3.class 기반\n* 4.hooks 기반\n\n## 1. start\n\n### server\n\n```bash\n$ cd server\n$ npm start\n```\n\n### client\n\n```bash\n$ cd client\n$ npm start\n```\n\n[localhost:3001](http://127.0.0.1:3001) 접속\n\n### start using docker\n\ndocker 기반 실행\n\n* create image\n\n```bash\n$ docker build -t react.tutorial -f ./Docker/Dockerfile .\n```\n\n[localhost:3001](http://127.0.0.1:3001) 접속\n\n\u003e 참고: Dockerfile에서 `cmd`는 docker run시 명령어를 전달하면 실행되지 않음. `docker --it {이미지} 명령어` OR `docker exec --it {컨테이너} 명령어`처럼 실행하면 CMD는 실행되지 않는다.\n\nOR\n\n```bash\n$ ./createImg.sh\n```\n\n* run \n\n```bash\n$ docker run --name r.1 -p 3001:80 -p 3000:3000 react.tutorial:latest\n```\n\nOR\n\n```bash\n$ ./createContainer.sh\n```\n\n* clear\n\n```bash\n$ docker stop r.1\n$ docker rm r.1\n$ docker rmi react.tutorial\n```\n\nor \n\n```bash\n$ ./clear.sh\n```\n\n## 2. socket 객체생성\n\n**`/client/src/index.js`**\n\n```js\nwindow.socket = io('http://127.0.0.1:3000');\n```\n\n하나의 app서는 하나의 소켓 객체를 생성\n\n소켓이 필요한 컴포넌트는 **`window.socket`** 이용\n\n만약, 컴포넌트마다 io(URL)을 하면 하나의 app에서 다수의 소켓 객체생성\n\n서버는 소켓 연결에 대해서 소켓 정보를 저장하고 있음.\n\n## 3. class 기반\n\n```js\nimport React from 'react';\n\nclass ClassBase extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      data: []\n    };\n\n    this.sendData = this.sendData.bind(this)\n    this.cb = this.cb.bind(this)\n  }\n\n  cb (msg) {\n    let dump = [...this.state.data]  \n    dump.push(msg)\n    console.log('classBase receive data update')\n    this.setState({\n      data: dump\n    })\n  }\n\n  componentDidMount () {\n    console.log('component mount')\n    window.socket.on('/data', this.cb)\n  }\n\n  componentWillUnmount () {\n    window.socket.off('/data', this.cb)\n  }\n\n  sendData() {\n    window.socket.emit('/data', {data: new Date().getTime()})\n  }\n\n  render () {\n    console.log('classBase renderer')\n    return (\n      \u003cdiv className=\"app\"\u003e\n        \u003ch2\u003eclassBase\u003c/h2\u003e\n        \u003cbutton onClick={this.sendData}\u003eclick\u003c/button\u003e\n        \u003cul\u003e\n          {this.state.data.map((item, idx) =\u003e (\n            \u003cli key={idx}\u003e{item.data}\u003c/li\u003e\n          ))}\n        \u003c/ul\u003e\n      \u003c/div\u003e\n    )\n  }\n}\n\nexport default ClassBase\n```\n\n해당 컴포넌트가 mount 됬을 때 on을 이용하여 이벤트 수신\n\nunmount가 됬다면 off이용\n\n## 4. hooks 기반\n\n```js\nimport React, {useState, useEffect} from 'react';\n\nconst HookBase = props =\u003e {\n  let [data, setData] = useState([])\n\n  useEffect(() =\u003e {\n    console.log('hookBase renderer')\n  })\n  useEffect(() =\u003e {\n    console.log('component mount')\n  }, [])\n\n  useEffect(() =\u003e {\n    let cb = msg =\u003e {\n      let dump = [...data]  \n      dump.push(msg)\n      console.log('hookBase receive data update')\n      setData(dump)\n    }\n    window.socket.on('/data', cb)\n    \n    // off가 없다면 data가 변경될 때마다 .on(/data)이 n개만큼 등록됨\n    return () =\u003e {\n      window.socket.off('/data', cb)\n    }\n  }, [data]) // data가 변경될 때마다 호출\n\n  const sendData = () =\u003e {\n    \n    window.socket.emit('/data', {data: new Date().getTime()})\n  }\n\n  return (\n    \u003cdiv className=\"App\"\u003e\n      \u003ch2\u003e hook base\u003c/h2\u003e\n      \u003cbutton onClick={sendData}\u003eclick\u003c/button\u003e\n      \u003cul\u003e\n        {data.map((item, idx) =\u003e (\n          \u003cli key={idx}\u003e{item.data}\u003c/li\u003e\n        ))}\n      \u003c/ul\u003e\n    \u003c/div\u003e\n  );\n}\n\nexport default HookBase;\n\n```\n\nhooks의 경우 data가 업데이트되면 다시 렌더링 될 때 return을 이용하여 기존 이벤트를 off한 후 다시 on\n\n만약, return에서 off를 해주지 않으면 data가 update 될 때마다 이벤트가 계속 등록됨\n\n\u003e useEffect는 두 번째 인자가 바뀔 때마다 호출됨.\n\n```js\nuseEffect(() =\u003e {\n\n})\n```\n\n두 번째 인자를 전달하지 않으면 해당 컴포넌트가 **`render`** 될 때마다 실행\n\n즉, state가 바뀔때마다 **`render`**가 이루어짐\n\n```js\nuseEffect(() =\u003e {\n\n}, [])\n```\n\n두 번째 인자로 빈 리스트([])를 전달하면 해당 컴포넌트가 mount 됬을 때 한번 호출\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpjt3591oo%2Freact-socket-tutorial","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpjt3591oo%2Freact-socket-tutorial","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpjt3591oo%2Freact-socket-tutorial/lists"}