Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chat Room #10

Open
hashedonemilliontimes opened this issue Feb 3, 2025 · 0 comments
Open

Chat Room #10

hashedonemilliontimes opened this issue Feb 3, 2025 · 0 comments
Assignees

Comments

@hashedonemilliontimes
Copy link
Collaborator

hashedonemilliontimes commented Feb 3, 2025

Users will be able to chat about items. If you have experience with Offerup or similar apps, that will be extremely valuable for this. When two users start talking about an item it will create a chat room. Every chat room will "belong" to an item and a pair of users. Every message will "belong" to that chat room. The models will look something like this, please familiarize yourselves with it. We will come back to the database later, not this week.

Image

Before we save the messages, lets start sending some. We will use socket.io for instant messaging.

  1. To install socket.io on the backend run: npm install socket.io

  2. Here is some starter code for the backend/server.js

// web socket for chat 
const http = require("http");
const server = http.createServer(app);
app.use(cors());

const { Server } = require("socket.io");


const io = new Server(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"],
  },
});

io.on("connection", (socket) => {
  console.log("User connected:", socket.id);

  socket.on("sendMessage", (message) => {
    io.emit("receiveMessage", message); // Broadcast to all clients
  });

  socket.on("disconnect", () => {
    console.log("User disconnected:", socket.id);
  });
});

const PORT = process.env.PORT || 0; // 0 lets the OS assign an available port

server.listen(PORT, () => {
  console.log(`Server running on port ${server.address().port}`);
});

Front End

  1. Now install socket.io-client for the front end. Run: npm install socket.io-client

  2. Create a new page called ChatPage.tsx on the front end in the src/pages folder. Soon we should also make a Messages.tsx page to view all the different chat rooms going on. Here is some starter code for the new page:

import { useEffect, useState } from "react";

const socket = new WebSocket("ws://localhost:3001");

function Chat() {
  const [message, setMessage] = useState("");
  const [chat, setChat] = useState([]);

  useEffect(() => {
    socket.onmessage = (event) => {
      setChat((prev) => [...prev, event.data]);
    };

    return () => socket.close();
  }, []);

  const sendMessage = () => {
    socket.send(message);
    setMessage("");
  };

  return (
    <div>
      <div>
        {chat.map((msg, i) => (
          <p key={i}>{msg}</p>
        ))}
      </div>
      <input value={message} onChange={(e) => setMessage(e.target.value)} />
      <button onClick={sendMessage}>Send</button>
    </div>
  );
}

export default Chat;
  1. Test and iterate. It looks like the server is going to use some available port and will have to notify the front end which port to use. Use plenty of console.log() to see what is going on.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants