Setup
Welcome to the Hyper-fetch Sockets setup guide! This guide will walk you through the essential first steps to get up and running with real-time communication in your application. We'll cover how to initialize the socket, create listeners for incoming events, and set up emitters to send data to your server.
- How to initialize the
Socketinstance. - How to create a
Listenerto receive events. - How to create an
Emitterto send events.
Initialize Socket
The first step is to initialize the Socket. It manages the basic configuration for the
connection to the server and all the sub-systems. We start by determining the url of our server.
import { Socket } from "@hyper-fetch/sockets";
export const socket = new Socket({ url: "ws://localhost:3000" });
Create Listener
Then, having already prepared the connection setup for the server, we use the socket method to create Listeners and assign types to them.
import { socket } from "socket";
type ChatMessageType = {
message: string;
};
export const onChatMessage = socket.createListener<ChatMessageType>()({
endpoint: "chat-message", // endpoint of the event
});
Create Emitter
Lastly, we need a way to send events to the server. We can create an Emitter and assign types to it.
import { socket } from "./socket";
type ChatMessageType = {
message: string;
};
// Optional
type AcknowledgementResponseType = {
value: string;
};
export const sendChatMessage = socket.createEmitter<ChatMessageType, AcknowledgementResponseType>()({
endpoint: "chat-message", // endpoint of the event
});
You've successfully set up the foundation for real-time communication with Hyper-fetch Sockets!
- You can initialize a
Socketwith a server URL. - You can create a
Listenerto handle incoming messages. - You can create an
Emitterto send messages to the server.
