├── frontend ├── public │ ├── robots.txt │ ├── favicon.ico │ ├── manifest.json │ └── index.html ├── src │ ├── App.css │ ├── index.css │ ├── reportWebVitals.js │ ├── index.js │ └── App.js └── package.json ├── .gitignore ├── backend └── run.py └── README.md /frontend/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /frontend/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ustropo/websocket-example/HEAD/frontend/public/favicon.ico -------------------------------------------------------------------------------- /frontend/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-header { 6 | background-color: #282c34; 7 | min-height: 100vh; 8 | display: flex; 9 | flex-direction: column; 10 | align-items: center; 11 | justify-content: center; 12 | font-size: calc(10px + 2vmin); 13 | color: white; 14 | } 15 | 16 | .App-link { 17 | color: #61dafb; 18 | } 19 | -------------------------------------------------------------------------------- /frontend/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /frontend/src/reportWebVitals.js: -------------------------------------------------------------------------------- 1 | const reportWebVitals = onPerfEntry => { 2 | if (onPerfEntry && onPerfEntry instanceof Function) { 3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 4 | getCLS(onPerfEntry); 5 | getFID(onPerfEntry); 6 | getFCP(onPerfEntry); 7 | getLCP(onPerfEntry); 8 | getTTFB(onPerfEntry); 9 | }); 10 | } 11 | }; 12 | 13 | export default reportWebVitals; 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | /frontend/node_modules 8 | node_modules/* 9 | 10 | # testing 11 | /coverage 12 | 13 | # production 14 | /build 15 | 16 | # misc 17 | .DS_Store 18 | .env.local 19 | .env.development.local 20 | .env.test.local 21 | .env.production.local 22 | 23 | npm-debug.log* 24 | yarn-debug.log* 25 | yarn-error.log* 26 | 27 | *__pycache__* 28 | 29 | .vscode* 30 | -------------------------------------------------------------------------------- /frontend/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import reportWebVitals from './reportWebVitals'; 6 | 7 | ReactDOM.render( 8 | 9 | 10 | , 11 | document.getElementById('root') 12 | ); 13 | 14 | // If you want to start measuring performance in your app, pass a function 15 | // to log results (for example: reportWebVitals(console.log)) 16 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 17 | reportWebVitals(); 18 | -------------------------------------------------------------------------------- /frontend/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /backend/run.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI, WebSocket 2 | import random 3 | 4 | # Create application 5 | app = FastAPI(title='WebSocket Example') 6 | 7 | @app.websocket("/ws") 8 | async def websocket_endpoint(websocket: WebSocket): 9 | print('a new websocket to create.') 10 | await websocket.accept() 11 | while True: 12 | try: 13 | # Wait for any message from the client 14 | await websocket.receive_text() 15 | # Send message to the client 16 | resp = {'value': random.uniform(0, 1)} 17 | await websocket.send_json(resp) 18 | except Exception as e: 19 | print('error:', e) 20 | break 21 | print('Bye..') 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WebSocket Example 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Server 6 | 7 | The server is implemented with FastAPI. First, install the dependencies: 8 | 9 | ``` 10 | pip install fastapi "uvicorn[standard]" 11 | ``` 12 | 13 | And then, run it: 14 | 15 | ``` 16 | uvicorn run:app 17 | ``` 18 | 19 | A server in the `localhost:8000` must be created. 20 | 21 | ## Client 22 | 23 | The client is implemented usign React and Recharts. 24 | 25 | Go to the frontend directory: 26 | 27 | ``` 28 | cd frontend 29 | ``` 30 | 31 | Install the dependencies: 32 | 33 | ``` 34 | yarn install 35 | ``` 36 | 37 | And run it: 38 | 39 | ``` 40 | yarn start 41 | ``` 42 | 43 | Open the browser in `localhost:3000` and you must see a chart being updated every second. 44 | -------------------------------------------------------------------------------- /frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "websocket", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^5.11.4", 7 | "@testing-library/react": "^11.1.0", 8 | "@testing-library/user-event": "^12.1.10", 9 | "react": "^17.0.1", 10 | "react-dom": "^17.0.1", 11 | "react-scripts": "4.0.2", 12 | "recharts": "^2.0.6", 13 | "web-vitals": "^1.0.1" 14 | }, 15 | "scripts": { 16 | "start": "react-scripts start", 17 | "build": "react-scripts build", 18 | "test": "react-scripts test", 19 | "eject": "react-scripts eject" 20 | }, 21 | "eslintConfig": { 22 | "extends": [ 23 | "react-app", 24 | "react-app/jest" 25 | ] 26 | }, 27 | "browserslist": { 28 | "production": [ 29 | ">0.2%", 30 | "not dead", 31 | "not op_mini all" 32 | ], 33 | "development": [ 34 | "last 1 chrome version", 35 | "last 1 firefox version", 36 | "last 1 safari version" 37 | ] 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /frontend/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 16 | 17 | 26 | Web Socket Example 27 | 28 | 29 | 30 |
31 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /frontend/src/App.js: -------------------------------------------------------------------------------- 1 | import './App.css'; 2 | import React from 'react'; 3 | import {AreaChart, CartesianGrid, Area, XAxis, YAxis} from 'recharts' 4 | 5 | 6 | class App extends React.Component { 7 | state = {data: [], count: 0} 8 | 9 | componentDidMount() { 10 | const ws = new WebSocket('ws://localhost:8000/ws') 11 | ws.onmessage = this.onMessage 12 | 13 | this.setState({ 14 | ws: ws, 15 | // Create an interval to send echo messages to the server 16 | interval: setInterval(() => ws.send('echo'), 1000) 17 | }) 18 | } 19 | 20 | componentWillUnmount() { 21 | const {ws, interval} = this.state; 22 | ws.close() 23 | clearInterval(interval) 24 | } 25 | 26 | onMessage = (ev) => { 27 | const recv = JSON.parse(ev.data) 28 | const {data, count} = this.state 29 | let newData = [...data] 30 | // Remove first data if we received more than 20 values 31 | if (count > 20) { 32 | newData = newData.slice(1) 33 | } 34 | newData.push({value: recv.value, index: count}) 35 | this.setState({data: newData, count: count + 1}) 36 | } 37 | 38 | render() { 39 | return ( 40 |
41 |
42 |

43 | WebSocket Example 44 |

45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 |
58 |
59 | ) 60 | } 61 | } 62 | 63 | export default App; 64 | --------------------------------------------------------------------------------