npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

flexi-chat-server

v1.0.3

Published

`flexi-chat-server` is an npm package that provides an easy way to create a Socket.IO server for real-time chat functionality. This package allows you to set up a chat server that supports user connections, messaging, and user management.

Downloads

9

Readme

flexi-chat-server

flexi-chat-server is an npm package that provides an easy way to create a Socket.IO server for real-time chat functionality. This package allows you to set up a chat server that supports user connections, messaging, and user management.

Features

  • Create a Socket.IO server with configurable CORS support.
  • Track active users and broadcast updates.
  • Send and receive messages between users.

Installation

To install flexi-chat-server, run:

npm install flexi-chat-server

Usage

Create a Socket Server

You can create a Socket.IO server by calling the createSocketServer function. This function sets up the server and allows you to specify the port and CORS origin.

const server = require("flexi-chat-server");

// Create a socket server on port 8800, allowing connections from http://localhost:3000
server
  .createSocketServer(8800, "http://localhost:3000")
  .then((data) => {
    console.log(data.message); // Output: "Socket server is running on port 8800"
  })
  .catch((error) => {
    console.error("Failed to start socket server:", error);
  });

API

createSocketServer(serverPort, clientOrigin)

  • Parameters:

    • serverPort (number): The port on which the Socket.IO server will listen.
    • clientOrigin (string): The origin allowed to connect to the server (e.g., "http://localhost:3000").
  • Returns: A Promise that resolves with a success message once the server is started successfully.

Event Listeners

The server supports the following events:

  1. connection: Triggered when a new client connects. Each connected client will receive an assigned socket ID.

  2. new-user-add:

    • Purpose: Adds a new user to the active users list.
    • Data: newUserId (string) - The ID of the new user.
    • Broadcasts: Updates the list of active users to all connected clients.
  3. disconnect:

    • Purpose: Handles user disconnections.
    • Broadcasts: Updates the list of active users to all connected clients.
  4. send-message:

    • Purpose: Sends a message from one user to another.
    • Data: An object containing:
      • receiverId (string) - The ID of the recipient user.
      • Other message data as needed.
    • Broadcasts: Sends the message to the specified recipient.
  5. recieve-message:

    • Purpose: Receives a message sent to the user.
    • Data: The message data sent by the sender.

Example

Here’s a basic example to demonstrate how you might use this package to set up a chat server:

const server = require("flexi-chat-server");

// Create a socket server
server
  .createSocketServer(8800, "http://localhost:3000")
  .then(() => {
    console.log("Socket server is running on port 8800");

    // Example of handling events on the client side (not part of the server code)
    const socket = io("http://localhost:8800");

    // Adding a new user
    socket.emit("new-user-add", "user123");

    // Sending a message
    socket.emit("send-message", {
      receiverId: "user456",
      content: "Hello, how are you?",
    });

    // Listening for incoming messages
    socket.on("recieve-message", (data) => {
      console.log("Message received:", data);
    });
  })
  .catch((error) => {
    console.error("Error starting socket server:", error);
  });

Error Handling

If the createSocketServer function encounters an error, it will reject the promise with the error message. Ensure to handle errors in your implementation using .catch().

Frontend Implementation

Here is an example of how to integrate flexi-chat-server with a React application:

  1. Setup the React Project

    Create a new React application:

    npx create-react-app chat-app
    cd chat-app
  2. Install Dependencies

    Install the socket.io-client package:

    npm install socket.io-client
  3. Create a Chat Component

    Create a new file Chat.js in the src directory:

    // src/Chat.js
    
    import React, { useEffect, useState } from "react";
    import io from "socket.io-client";
    
    const socket = io("http://localhost:8800"); // Update with your server's URL
    
    function Chat() {
      const [message, setMessage] = useState("");
      const [messages, setMessages] = useState([]);
      const [userId, setUserId] = useState("");
      const [receiverId, setReceiverId] = useState("");
    
      useEffect(() => {
        // Listen for incoming messages
        socket.on("recieve-message", (data) => {
          setMessages((prevMessages) => [...prevMessages, data]);
        });
    
        // Add new user
        if (userId) {
          socket.emit("new-user-add", userId);
        }
    
        return () => {
          socket.off("recieve-message");
        };
      }, [userId]);
    
      const handleSendMessage = () => {
        if (message.trim() && receiverId) {
          socket.emit("send-message", { receiverId, content: message });
          setMessages((prevMessages) => [
            ...prevMessages,
            { content: message, senderId: userId },
          ]);
          setMessage("");
        }
      };
    
      return (
        <div>
          <h2>Chat Application</h2>
          <div>
            <input
              type="text"
              placeholder="Your User ID"
              value={userId}
              onChange={(e) => setUserId(e.target.value)}
            />
            <input
              type="text"
              placeholder="Receiver ID"
              value={receiverId}
              onChange={(e) => setReceiverId(e.target.value)}
            />
          </div>
          <div>
            <textarea
              rows="5"
              placeholder="Type your message here..."
              value={message}
              onChange={(e) => setMessage(e.target.value)}
            />
            <button onClick={handleSendMessage}>Send</button>
          </div>
          <div>
            <h3>Messages</h3>
            <ul>
              {messages.map((msg, index) => (
                <li key={index}>
                  {msg.senderId}: {msg.content}
                </li>
              ))}
            </ul>
          </div>
        </div>
      );
    }
    
    export default Chat;
  4. Update the App Component

    Replace the contents of src/App.js with:

    // src/App.js
    
    import React from "react";
    import "./App.css";
    import Chat from "./Chat";
    
    function App() {
      return (
        <div className="App">
          <Chat />
        </div>
      );
    }
    
    export default App;
  5. Start the React App

    Run your React application:

    npm start

License

This package is licensed under the ISC License. Here’s how you can update the README.md file to include the frontend implementation code snippet for the React application: