socket.io.wrap

1.0.1 • Public • Published

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;

Readme

Keywords

none

Package Sidebar

Install

npm i socket.io.wrap

Weekly Downloads

1

Version

1.0.1

License

ISC

Unpacked Size

3.35 kB

Total Files

5

Last publish

Collaborators

  • mahaveer1013