SocketIo, Node and React
Node server
const express = require('express')
const app = express()
const cors = require('cors')
const socketio = require('socket.io')
const router = require('./router/chat')
app.use(cors())
app.use(express.json())
const port = process.env.PORT || 3001
app.use(router)
// const server =
const server = app.listen(port, ()=>{
console.log('server runs on port ', port);
})
const io = socketio(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"]
}
})
let count = 0
io.on('connection', (socket)=>{
console.log('connect to the frontend');
socket.emit('count', count)
socket.on('increase', ()=>{
count++
io.emit('count', count)
})
socket.on('disconnect', ()=>{
console.log('user left');
})
})
React part
import React, { useEffect } from 'react'
import {io} from 'socket.io-client'
const ENDPOINT = 'http://localhost:3001/'
let server;
const App = () => {
useEffect(()=>{
server = io(ENDPOINT)
server.on('count', (count)=>{
console.log('hello world', count);
})
})
const click = ()=>{
server.emit('increase')
}
return (
<div>
<h1> Chat </h1>
<button onClick={click}> Click </button>
</div>
)
}
export default App