socket.io.wrap
v1.0.1
Published
A simple and flexible wrapper for Socket.IO that streamlines real-time communication for both server and client applications.
Downloads
12
Readme
socket.io.wrap
A simple and flexible wrapper for Socket.IO that streamlines real-time communication for both server and client applications.
Features
- Unified API: Handle Socket.IO connections with a consistent interface for both Node.js servers and React clients.
- Easy Integration: Quickly set up event listeners and emit events with minimal configuration.
- Cross-Environment Support: Works seamlessly in both Node.js and browser environments, simplifying full-stack development.
Installation
To install the package, use npm:
npm install socket.io.wrap
SERVER SIDE
// server.js
const http = require('http');
const { ServerWrapper } = require('socket.io.wrap');
// Create an HTTP server
const server = http.createServer();
// Create a new instance of the Socket.IO wrapper
const socketWrapper = new ServerWrapper(server);
// Handle incoming messages
socketWrapper.on('message', (data) => {
console.log('Message received:', data);
});
// Emit a welcome message to new clients
socketWrapper.emit('welcome', 'Welcome to the server!');
// Start the server
server.listen(3000, () => {
console.log('Server running on port 3000');
});
CLIENT SIDE
// App.js
import React, { useEffect } from 'react';
import { ClientWrapper } from 'socket.io.wrap';
// Initialize the Socket.IO client
const socket = new ClientWrapper('http://localhost:3000');
function App() {
useEffect(() => {
// Listen for incoming messages
socket.on('message', (data) => {
console.log('Message received:', data);
});
// Clean up on component unmount
return () => {
socket.disconnect();
};
}, []);
const sendMessage = () => {
socket.emit('sendMessage', { text: 'Hello from React!' });
};
return (
<div>
<button onClick={sendMessage}>Send Message</button>
</div>
);
}
export default App;