2

I am new to UDP/datagram package in Node, please pardon me if wrong in my conceptual understanding here.

I tried creating an abstract class UdpClient using NodeJS dgram package

Code is in TypeScript

import { deserialize, serialize } from "v8"

type ClientInfo = {
    address: string,
    port: number
}

type Message = {
    messageUuid: string,
    type: string,
    body: any
}

class UdpClient {
    socket: Socket
    constructor(onMessage: (message: Message) => any) {
        this.socket = createSocket("udp4")
        this.socket.on("message", (msg) => {
            const message = deserialize(msg)
            onMessage(message)
        })
        this.socket.on("error", (err) => {
            console.log({ err });
        })
    }
    send = (rinfo: ClientInfo, message: Message) => () => {
        console.log(this.socket.ref.toString());
        this.socket.on('error', (err)=>{
            console.log("err", err);
        })
        this.socket.send(
            serialize(message),
            rinfo.port,
            rinfo.address,
            (err) => {
                console.log(err);
            }
        )
    }
}

Implementation of the above class

import { v4 as uuid } from "uuid"
const serverInfo = {
        port: 65530,
        address: "127.0.0.1"
    }
const alice = new UdpClient((message)=>{
   console.log("Alice:", message);
})
alice.send(serverInfo, {
   type: 'ping',
   messageUuid: uuid(),
   body: null
})

Result of Above code:-

  • No message received by Server
  • No error displayed here
        this.socket.on('error', (err)=>{
            console.log("err", err);
        })

Whereas if I try simple flow by creating UDP socket object and use it directly as examples here Node JS docs UDP/Datagram

const serverInfo = {
        port: 65530,
        address: "127.0.0.1"
    }
const alice = createSocket('udp4')
const message = {
   type: 'ping',
   messageUuid: uuid(),
   body: null
}
alice.send(
    serialize(message),
    serverInfo.port,
    serverInfo.address
)

Result of Above code:-

  • Message is received by the server

What could be the issue with storing the socket as member of my UdpClient class?

  • It has something to do with TS compiler creating function type classes?
  • Something wrong in my code?
  • Or some intrinsic property of socket object made with createSocket function?

And if my approach is wrong, please suggest the right way to do it.

rishav
  • 288
  • 2
  • 8
  • Having the same issue in 2023, seems to work just fine when the socket is not a class member. Did you ever solve this? – pure_bordem Apr 21 '23 at 00:26

0 Answers0