A web socket is a protocol that provides bidirectional and full-duplex communication channels.
Traditionally, when we are on a web page, we communicate with the server through one-way communication. However, with web sockets, communication can be done by both us and the server. Hence, it is no longer us talking to the server alone.
One example of a web socket is a website that tells you the number of people online. Another example of a web socket is real-time chat applications.
Below is the Feact code that emits an event that will be fired in the server. It establishes a two-way connection with the server running on http://localhost:5000
.
import {io} from "socket.io-client";const ENDPOINT = "http://localhost:5000";const socket = io(ENDPOINT);useEffect(() => {// ... other codes// Emitting an event that will trigger in the backendsocket.emit("reply");// ... other codes}, [])
// ... other codesconst io = require('socket.io')(server);io.on('connection', client => {client.on('reply', () => { console.log("a reply detected!")}); // listen to the event});server.listen(PORT, ()=>{console.log("Application running successfully on port: "+PORT);});
When we run the code above, the following error will be thrown in the console:
The reason for this is that there was no configuration for cors
in the socket.io implementation of the server-side.
Even with the cors
enabled on the server-side, there will still be an error unless there are cors
configured along with the socket.io implementation.
var cors = require('cors');
app.use(cors());
The error is simple to fix. Add cors
and the origin
that can communicate with the server, and that’s all!
const io = require('socket.io')(server, {cors: {origin: "*"}});
In the code above, I added a wildcard as my
origin
because I would like anyorigin
to access it.