Plain UDP Socket and Client
- Fast — little overhead above UDP to send messages
- Simple — used well-known Node streams to manipulate and move data
- Zero-dependency
- ESM and CJS
npm i --save socket-udp
//app.js
import { UDPClient } from 'socket-udp'
const client = new UDPClient({ port: 44002 })
client.write(Buffer.from('Hello, World!', 'utf8'))
//server.js
import { UDPSocket } from 'socket-udp'
const socket = new UDPSocket({ port: 44002 })
for await (const message of socket) {
console.log(message.toString('utf8'))
}
After just start the server node server.js
and start your app node app.js
. That's all, you've just sent and received message.
Extends Writabable
Stream
Extends WritableOptions and dgram.SocketOptions
options
<object>
– optionaltype
<'udp4' | 'udp6'>
– optional. Default'udp4'
port
<string | number>
– optional. Target port. Default44002
address
<string>
– optional. Target address. Default'127.0.0.1'
or'::1'
bindAddress
<dgram.BindOptions>
– optional.port
<integer>
— optional.address
<string>
— optional.exclusive
<boolean>
— optional.fd
<integer>
— optional.
origin
:<dgram.Socket>
port
:<number>
address
:<string>
family
:<string>
allowWrite
:<boolean>
targetPort
:<number>
targetAddress
:<number>
Emitted when the client "establishes" udp connection.
import { UDPClient } from 'socket-udp'
const client = new UDPClient({ port: 44002 })
client.write(Buffer.from('hi!', 'utf8'))
Extends Readable
Stream
It is a UDP socket in readable stream
form.
Extends ReadableOptions and dgram.SocketOptions
options
<object>
– requiredtype
<'udp4' | 'udp6'>
– optional. Default'udp4'
port
<string | number>
– optional. Default44002
address
<string>
– optional. Default'127.0.0.1'
or'::1'
pushMeta
<boolean>
– optional. Will push not a raw message, but an object with remoteInfo. Message data will be placed in fieldbody
. Defaultfalse
origin
:<dgram.Socket>
port
:<number>
address
:<string>
family
:<string>
allowPush
:<boolean>
All Readable
events of course and:
Emitted when socket started and ready to receive data.
Emitted right after a message was received
message
<Buffer>
handleMessage
(body: Buffer, head: MessageHead) => void
– handles raw messages from dgram.Socket. If you need to handle data before any manipulation then overwrite it.
import fs from 'node:fs'
import { UDPSocket } from 'socket-udp'
const socket = new UDPSocket()
const writer = fs.createWriteStream('/some/path')
socket.pipe(writer)
import { UDPSocket } from 'socket-udp'
const socket = new UDPSocket({ port: 44002, pushMeta: true })
for await (const { address, port, body } of socket) {
console.log(`From ${address}:${port} you recieved`, JSON.parse(body.toString('utf8')))
}
<number>
:44002
License (MIT)