Skip to content

Message socket

Alvin Cheng edited this page Apr 23, 2023 · 4 revisions

Description

This is the message socket, this socket as the name suggests sends a message by emitting it to the clients and storing it in the database by using the 'server-message' event. As I mentioned before, we are NOT using the default websockets, we are using the socket.io library for web sockets. Anyways, this socket excepts a 'message' argument for the message to be sent (This argument contains an object which contains id, user(The sender), content, room(Room of the message).), a 'key' argument for the API key and a 'token' for the response token.

If you would like to listen for a message, you can listen to the 'client-message' this event will return the message sent when a new message is sent with the 'server-message'. There is an example below on how to use it.

What is a response token??

A response token is a token to send a request to if an error occurs.

Example

const io = require("socket.io");

const socket = io("<URL>", { transports: ["websocket"] });

const message = {
  id: "<ID>",
  user: "<SENDER>",
  content: "<CONTENT>",
  room: "<ROOM>",
};

// Send to server
socket.emit("server-message", message, "<API_KEY>", "<TOKEN>");

socket.on("client-message:room(<ROOM>)", (message) => {
  /* This will run when a message of the same room is sent */
  console.log(message);
});
Clone this wiki locally