The socket.send() method is an inbuilt application programming interface of class Socket within dgram module which is used to send the message from one socket to another.
Syntax:
socket.send(msg[, offset, length][, port][, address][, callback])
Parameters: This method takes the following parameter:
- msg: Message to be sent.
- offset: Offset in the buffer where the message starts.
- length: Number of bytes in the message.
- port: Destination port.
- address: Destination hostname or IP address.
- callback: Called when the message has been sent.
Return Value: This method does not return any value.
Example 1: In this example, we will see the use of socket.send() Method
Filename: index.js
Javascript
const dgram = require( 'dgram' );
let client = dgram.createSocket( "udp4" );
let server = dgram.createSocket( "udp4" );
server.on( "message" , function (msg) {
process.stdout.write( "UDP String: " + msg + "\n" );
process.exit();
})
.bind(1234, () => {
const size = server.ref();
console.log(size.eventNames());
});
client.send( "Hello" , 0, 7, 1234, "localhost" );
|
Output:
[ 'message' ]
UDP String: Hello
Example 2: In this example, we will see the use of a socket.send() Method
Filename: index.js
Javascript
const dgram = require( 'dgram' );
let client = dgram.createSocket( "udp4" );
let server = dgram.createSocket( "udp4" );
server.on( "message" , function (msg) {
process.stdout.write( "UDP String: " + msg + "\n" );
process.exit();
});
server.on( 'listening' , () => {
const address = server.address();
console.log(
`server listening ${address.address}:${address.port}`);
});
server.bind(1234, () => {
const size = server.ref();
console.log(size.eventNames());
});
client.send( "Hello" , 0, 7, 1234, "localhost" , (err) => {
if (err) throw err;
console.log( "message sent" );
});
|
Output:
server listening 0.0.0.0:1234
[ 'message', 'listening' ]
message sent
UDP String: Hello
Run the index.js file using the following command:
node index.js
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/dgram.html#dgram_socket_send_msg_offset_length_port_address_callback
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!