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
1
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:
connection
: Triggered when a new client connects. Each connected client will receive an assigned socket ID.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.
disconnect
:- Purpose: Handles user disconnections.
- Broadcasts: Updates the list of active users to all connected clients.
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.
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:
Setup the React Project
Create a new React application:
npx create-react-app chat-app cd chat-app
Install Dependencies
Install the
socket.io-client
package:npm install socket.io-client
Create a Chat Component
Create a new file
Chat.js
in thesrc
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;
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;
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: