diff --git a/Connection.js b/Connection.js index e69de29..004bf8f 100644 --- a/Connection.js +++ b/Connection.js @@ -0,0 +1,21 @@ +const socketIO = require('socket.io'); + +const io = (server) => { + return socketIO(server, { + cors: { + origin: "http://localhost:3000" + } + }); +} + +const connection = (io) => { + io.on('connection', (socket) => { + console.log(`User ${socket.id} connected`); + + socket.on('disconnect', () => { + console.log(`User ${socket.id} disconnected`) + }) + }) +} + +module.exports = { io, connection } \ No newline at end of file diff --git a/client/src/App.jsx b/client/src/App.jsx index 20e53cd..f1d72d5 100644 --- a/client/src/App.jsx +++ b/client/src/App.jsx @@ -1,19 +1,23 @@ import { useState, useEffect } from 'react' import logo from './logo.svg' -import { io } from 'socket.io-client' +import io from 'socket.io-client' // import './App.css' function App() { + const [socket, setSocket] = useState(); + useEffect(() => { - const socket = io('ws://localhost:8000'); + const newSocket = io("http://localhost:8000"); + setSocket(newSocket); - socket.on('connect', ()=>console.log(socket.id)) - socket.on('connect_error', ()=>{ - setTimeout(()=>socket.connect(),5000) + return () => newSocket.close(); + }, [setSocket]); + + useEffect(() => { + socket.on('connection', () => { + console.log(socket.id); }) - - return () => socket.close(); - }, []); + }, [socket]); return (
diff --git a/index.js b/index.js index c6217f8..a974dcf 100644 --- a/index.js +++ b/index.js @@ -1,29 +1,23 @@ const express = require('express'); -const app = express(); const cors = require('cors'); - -app.use(cors()); - const http = require('http'); + +const { io, connection } = require("./Connection"); + +const app = express(); +app.use(cors()); const server = http.createServer(app); -const socketIO = require('socket.io'); +const socketIOMiddleware = (req, res, next) => { + req.io = io; + next(); +} -const io = socketIO(server, { - cors: { - origin: 'http://localhost:3000' - } -}); - -io.on('connection', (socket) => { - console.log('client connected: ' + socket.id); -}); - -app.use('/', (req, res) => { - +server.use('/', (req, res) => { + res.send(connection(io(server))); }) -app.listen(8000, (err) => { +server.listen(8000, (err) => { if (err) console.log(err); console.log("Listening on 8000"); }) \ No newline at end of file