SvelteKit + Socket.io server deployed on deno

The finalĀ  demo , what we are gonna build

Loading...

Socket.io server

Here we instantiate a Server class, with appropriate options


   import   {serve}  from  "https://deno.land/std@0.208.0/http/server.ts";
   import   {Server}  from  "https://deno.land/x/socket_io@0.2.0/mod.ts";
        
     const io  = new Server({
          cors: {
           origin: [
              "https://localhost:5173",
              "https://socket-deno.netlify.app/"",
            ],
            credentials: true,
            methods: ["GET", "POST"],
            },
          });

            
      io.on("connection", (socket)=>{ 
       console.log(`socket ${socket.id} connected`);
        
        socket.on("disconnect", (reason)=>{ 
         console.log(`socket ${socket.id} disconnected due to ${reason}`);
        });
        socket.on("chatMsg", (data)=>{

           console.log(`Recieved data : ${data}`);

         socket.broadcast.emit("chatMsg", `${data} [${socket.id}]`);
         });
       })

        console.log("Server listening on port 3000!");
        
        await serve(io.handler(), 
          port: 3000,
        );
     
      

Kit code

In client side SvelteKit app, we connect to the server with the public url we got by deploying our server on deno

// lib/socket.ts

   import {io} from "socket.io-client"

          export const socket = io('https://socket-sveltekit.deno.dev/',{
		       transports:["websocket"]
         })
        

Now we build the UI, when the server broadcasts and emits the chatMsg event we create a new li node and append it to the chatbox.

//+page.svelte

  <script lang="ts">
        import  { browser  } from "$app/environment";
        import  { socket  } from "$lib/socket";
    
        $: chatid = "...";
        socket.on("connect", () => {
        console.log(`Connected to ${socket.id}`);
            chatid = socket.id;
        });
        let msg = browser ? document.getElementById("chat-box") : null;
    
        socket.on("chatMsg", (data: string | null) => {
         let newMsg = document.createElement("li");
         newMsg.classList.add("text-neutral-600", "text-lg", "bg-gray-300","rounded-lg");
            newMsg.textContent = data;
    
            msg?.appendChild(newMsg);
            msg?.scrollTo(0, msg.scrollHeight);
        });
    
        let emitter = (data: string) => {
         socket.emit("chatMsg", data);
    
            let newMsg = document.createElement("li");
            newMsg.classList.add("text-neutral-400", "text-lg");
            newMsg.textContent = `${data} [${socket.id}]`;
    
            msg?.appendChild(newMsg);
    
            msg?.scrollTo(0, msg.scrollHeight);
        }
    </script>
    
   <main class="bg-gray-800 h-dvh w-full flex justify-center items-center">
   <h1 class="absolute text-gray-300 top-1">
            Your chat id is :  {chatid }
            </h1>
            <div
            class="relative flex flex-col overflow-y-auto min-w-[70%] max-w-[85%] bg-gray-900 h-[75%] text-stone-500 rounded-xl"
        >
        <ul id="chat-box" class="my-4 break-words"></ul>
    
        <input
                type="text"
                on:keypress={( { key, target  }) =>  {
                    if (key != "Enter") return;
                    emitter(target?.value);

                    target.value=''
                    } }
                class="absolute bottom-1 w-[90%] self-center bg-zinc-600 text-stone-300 p-3 rounded-lg"
                />
                </div>
     </main>
    

Advantages and Drawbacks

The Advantages of this approach

  • - Separate server distributes the load, rather than all load on current one.
  • - Performance : It can provide high efficiency, as you seperate client app and server app logics.
  • - Can increase productivity due seperate client and server maintenance.

Drawbacks

  • - Can be hectic to maintain and develop server and client logic simultaneously.
  • - As server grows and scale, it can cost more to promote the resources.
  • - Server side logic needs to be secure.