Socket.IO server for Deno

Overview

Socket.IO server for Deno

An implementation of the Socket.IO protocol for Deno.

Table of content:

Usage

import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { Server } from "https://deno.land/x/[email protected]/mod.ts";

const io = new Server();

io.on("connection", (socket) => {
  console.log(`socket ${socket.id} connected`);

  socket.emit("hello", "world");

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

await serve(io.handler(), {
  port: 3000,
});

And then run with:

$ deno run --allow-net index.ts

Like the Node.js server, you can also provide types for the events sent between the server and the clients:

interface ServerToClientEvents {
  noArg: () => void;
  basicEmit: (a: number, b: string, c: Buffer) => void;
  withAck: (d: string, callback: (e: number) => void) => void;
}

interface ClientToServerEvents {
  hello: () => void;
}

interface InterServerEvents {
  ping: () => void;
}

interface SocketData {
  user_id: string;
}

const io = new Server<
  ClientToServerEvents,
  ServerToClientEvents,
  InterServerEvents,
  SocketData
>();

Options

path

Default value: /socket.io/

It is the name of the path that is captured on the server side.

Caution! The server and the client values must match (unless you are using a path-rewriting proxy in between).

Example:

const io = new Server(httpServer, {
  path: "/my-custom-path/",
});

connectTimeout

Default value: 45000

The number of ms before disconnecting a client that has not successfully joined a namespace.

pingTimeout

Default value: 20000

This value is used in the heartbeat mechanism, which periodically checks if the connection is still alive between the server and the client.

The server sends a ping, and if the client does not answer with a pong within pingTimeout ms, the server considers that the connection is closed.

Similarly, if the client does not receive a ping from the server within pingInterval + pingTimeout ms, the client also considers that the connection is closed.

pingInterval

Default value: 25000

See pingTimeout for more explanation.

upgradeTimeout

Default value: 10000

This is the delay in milliseconds before an uncompleted transport upgrade is cancelled.

maxHttpBufferSize

Default value: 1e6 (1 MB)

This defines how many bytes a single message can be, before closing the socket. You may increase or decrease this value depending on your needs.

allowRequest

Default value: -

A function that receives a given handshake or upgrade request as its first parameter, and can decide whether to continue or not.

Example:

const io = new Server({
  allowRequest: (req, connInfo) => {
    return Promise.reject("thou shall not pass");
  },
});

cors

Default value: -

A set of options related to Cross-Origin Resource Sharing (CORS).

Example:

const io = new Server({
  cors: {
    origin: ["https://example.com"],
    allowedHeaders: ["my-header"],
    credentials: true,
  },
});

editHandshakeHeaders

Default value: -

A function that allows to edit the response headers of the handshake request.

Example:

const io = new Server({
  editHandshakeHeaders: (responseHeaders, req, connInfo) => {
    responseHeaders.set("set-cookie", "sid=1234");
  },
});

editResponseHeaders

Default value: -

A function that allows to edit the response headers of all requests.

Example:

const io = new Server({
  editResponseHeaders: (responseHeaders, req, connInfo) => {
    responseHeaders.set("my-header", "abcd");
  },
});

Logs

The library relies on the standard log module, so you can display the internal logs of the Socket.IO server with:

import * as log from "https://deno.land/[email protected]/log/mod.ts";

await log.setup({
  handlers: {
    console: new log.handlers.ConsoleHandler("DEBUG"),
  },
  loggers: {
    "socket.io": {
      level: "DEBUG",
      handlers: ["console"],
    },
    "engine.io": {
      level: "DEBUG",
      handlers: ["console"],
    },
  },
});

License

ISC

You might also like...

A command-line tool to manage Deno scripts installed via deno install

🏞️ nublar nublar is a command-line tool to manage your scripts installed via deno install. 🛳️ Installation deno install --allow-read --allow-write -

Dec 26, 2022

Monolithic repo for api server, image server, web server

Onsecondary Market Deployed at https://market.onsecondary.com Monolithic repo for api server, image server, web server TODO -use a script to cull expi

Jan 11, 2022

To keep online organized data and be able to add listeners in certain paths by socket.io and http clients

To keep online organized data and be able to add listeners in certain paths by socket.io and http clients

The purpose of this project is to create a state machine server to keep organized data and be able to add listeners with socket.io in specific paths and in addition to providing a possible form of messages between socket.io clients.

Mar 19, 2022

I built a full-stack project using Node, Express, Mongo, webRTC, socket.io, and of course React JS. This project is inspired by the awesome Clubhouse 😊

codershouse-mern - This Project is Under Development. Below are some of the implemented interface and the remaining features will be updated in future

Nov 18, 2022

A social network app cloned from Instagram built with Next.Js, Socket.IO and a lots of other new stuff.

A social network app cloned from Instagram built with Next.Js, Socket.IO and a lots of other new stuff.

Instagram Noob ⚡ A social network app cloned from Instagram built with Next.Js, Socket.IO and a lots of other new stuff. Live Demo: https://instagram-

Oct 19, 2022

Node.js implementation of the Socket SDK client

SYNOPSIS A Node.js adapter for the Socket SDK DESCRIPTION Socket SDK uses a simple uri-based protocol for brokering messages between the render proces

Dec 28, 2022

Simple google docs thing in Remix using socket.io.

This is just a simple google docs thing, me playing around with Remix and sockets. TODO: from socket.io to yjs sockets, support CRDT. Installation Aft

Apr 19, 2022

a chatt app build using node , express and socket IO , it has many rooms

RealTime-chatt-app you can view the app here : https://bit.ly/3zce4ON a chatt app build using node , express and socket IO . used to public chatt room

Aug 31, 2022

A complete application tutorial to show how to implement the Web Socket protocol using only Node.js builtin modules

A complete application tutorial to show how to implement the Web Socket protocol using only Node.js builtin modules

Web Socket application using only Node.js built-in modules About Welcome, this repo is part of my youtube video about Building a complete application

Dec 19, 2022
Comments
  • Client connected but it doesn't receive anything

    Client connected but it doesn't receive anything

    The client is connected fine and can send and receive events, but some times the server doesn't recieve any event and the client is still connected.

    The way to reproduce it: Start and stop the client a few times, until it stops receiveing the pong message.

    client:

    const socket = io("http://localhost:8080");
    
    socket.on("pong", ({ datetime }) => {
        console.log(`Response time (${(Date.now() - datetime)}ms)`)
    });
    
    socket.on("connect", () => {
        console.log(`Connected! ${socket.id}`);
        
        setInterval(() => {
            socket.emit('ping', { datetime: Date.now() });
        }, 1000);
    });
    
    socket.connect();
    

    server:

    const io = new Server();
    
    io.on("connection", (socket) => {
        console.log(`socket ${socket.id} connected`);
        
        socket.on('ping', (data) => {
            console.log(`[${socket.id}]: ping!`)
            socket.emit('pong', data)
        });
    });
    
    await serve(io.handler(), {
        port: 8080,
    });
    
    bug 
    opened by pagoru 3
  • TypeError: Headers are immutable

    TypeError: Headers are immutable

    Trying to setup Websockets with Deno & IO. Upon establishing connection I'm getting this pesky error - any idea how to fix this?

    TypeError: Headers are immutable.
        at Headers.set (deno:ext/fetch/20_headers.js:384:15)
        at https://deno.land/x/[email protected]/packages/engine.io/lib/transports/websocket.ts:60:24
        at Headers.forEach (deno:ext/webidl/00_webidl.js:1001:13)
        at WS.onRequest (https://deno.land/x/[email protected]/packages/engine.io/lib/transports/websocket.ts:59:21)
        at Server.handleRequest (https://deno.land/x/[email protected]/packages/engine.io/lib/server.ts:217:35)
        at async Server.#respond (https://deno.land/[email protected]/http/server.ts:298:18)
    

    Server:

    const io = new Server({ cors: { origin: 'http://localhost:3000' } });
    
    io.on('connection', socket => {
      console.log(`Socket ${socket.id} connected`);
    
      socket.on('disconnect', reason => {
        console.log(`Socket ${socket.id} disconnected due to ${reason}`);
      });
    });
    
    await serve(io.handler(), {
      port: 8080,
    });
    

    Client:

    const socket = io('ws://localhost:8080');
    
      socket.on('connection', () => {
        console.log('Connection established.');
      });
    
    opened by mxnkarou 2
  • [feature] implement MongoDB adapter

    [feature] implement MongoDB adapter

    Needed: https://github.com/denodrivers/mongo/issues/261

    Reference: https://socket.io/docs/v4/mongo-adapter/ Node.js impl: https://github.com/socketio/socket.io-mongo-adapter

    enhancement 
    opened by darrachequesne 0
  • [feature] implement Postgres adapter

    [feature] implement Postgres adapter

    Needed: https://github.com/denodrivers/postgres/issues/39 (potential workaround: https://deno.land/x/postgresjs)

    Reference: https://socket.io/docs/v4/postgres-adapter/ Node.js impl: https://github.com/socketio/socket.io-postgres-adapter

    enhancement 
    opened by darrachequesne 0
Releases(0.2.0)
  • 0.2.0(Oct 10, 2022)

    Bug Fixes

    • engine: properly pause the polling transport during upgrade (c706741), closes #4
    • restore socket.to() and socket.except() methods (4ce5f64), closes #3
    • server: send events once the handshake is completed (518f534)

    Features

    • implement catch-all listeners (333dfdd)

    Syntax:

    io.on("connection", (socket) => {
      socket.onAnyIncoming((event, ...args) => {
        // ...
      });
    
      socket.onAnyOutgoing((event, ...args) => {
        // ...
      });
    });
    
    • implement the Redis adapter (39eaa0e)
    import { serve } from "https://deno.land/[email protected]/http/server.ts";
    import {
      createRedisAdapter,
      createRedisClient,
      Server,
    } from "https://deno.land/x/[email protected]/mod.ts";
    
    const [pubClient, subClient] = await Promise.all([
      createRedisClient({
        hostname: "localhost",
      }),
      createRedisClient({
        hostname: "localhost",
      }),
    ]);
    
    const io = new Server({
      adapter: createRedisAdapter(pubClient, subClient),
    });
    
    await serve(io.handler(), {
      port: 3000,
    });
    

    Diff: https://github.com/socketio/socket.io-deno/compare/0.1.1...0.2.0

    Source code(tar.gz)
    Source code(zip)
  • 0.1.1(Sep 16, 2022)

    Bug Fixes

    • disallow duplicate WebSocket connections with same sid (193a9b5)
    • disallow mismatching transport (6b2cc16)
    • prevent crash when using custom headers (dfe3122)
    • send a "noop" packet when transport is already closed (3b1eb82)

    Diff: https://github.com/socketio/socket.io-deno/compare/0.1.0...0.1.1

    Source code(tar.gz)
    Source code(zip)
  • 0.1.0(Sep 12, 2022)

Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Opinionated collection of TypeScript definitions and utilities for Deno and Deno Deploy. With complete types for Deno/NPM/TS config files, constructed from official JSON schemas.

Schemas Note: You can also import any type from the default module, ./mod.ts deno.json import { type DenoJson } from "https://deno.land/x/[email protected]

deno911 2 Oct 12, 2022
TikTokLive-Widget: A socket client/server program that exposes a widget with alerts (such as gifts, followers ...) for a specific user streaming on Tik Tok Live platform

TikTokLive-Widget: A socket client/server program that exposes a widget with alerts (such as gifts, followers ...) for a specific user streaming on Tik Tok Live platform

null 3 Dec 3, 2022
This is a simple boilerplate for a Deno website, deployed with Deno Deploy.

Simple Deno Website Boilerplate This is a simple website boilerplate built using Deno and deployed using Deno Deploy. Demo at simple-deno-website-boil

Bruno Bernardino 15 Dec 3, 2022
TypeSafe MongoDB Atlas Data API SDK for Deno & Deno Deploy

Atlas SDK atlas_sdk is a TypeSafe MongoDB Atlas Data API SDK for Deno & Deno Deploy Links Docs Import Replace LATEST_VERSION with current latest versi

Erfan Safari 20 Dec 26, 2022
Deno bindings for yoga, using Deno FFI.

deno_yoga Deno bindings for yoga, using Deno FFI. Usage flags: --allow-ffi: Requires ffi access to "yogacore.dll", "libyogacore.so", "libyogacore.dyli

迷渡 6 Feb 11, 2022
🛣️ A tiny and fast http request router designed for use with deno and deno deploy

Rutt Rutt is a tiny http router designed for use with deno and deno deploy. It is written in about 200 lines of code and is pretty fast, using an exte

Denosaurs 26 Dec 10, 2022
A small, but powerful HTTP library for Deno & Deno Deploy, built for convenience and simplicity

Wren Wren is a small, but powerful HTTP library for Deno & Deno Deploy, built for convenience and simplicity. convenient aliases for HTTP responses au

Jakub Neander 69 Dec 12, 2022
deno-ja (Deno Japanese community) showcase

Showcase Deno本家よりも気軽に作ったものを公開できるようなShowcaseです。 スクリーンショットの撮影方法 短めのidを決めていただいて、下記のようにスクリプトを実行してください。 deno task screenshot [url] [id] ※エラーが出る場合は、下記を実行してみ

deno-ja 17 Oct 28, 2022