My html page

JavaScript socket

JavaScript socket tutorial shows how to work with sockets in JavaScript.

In programming, a is an endpoint of a communication between two programs running on a network. Sockets are used to create a connection between a client program and a server program.

Sockets API is available in the Node.js net module.

Note: In networking, the term socket has a different meaning. It is used for the combination of an IP address and a port number.

JS socket HEAD request

A HEAD request is an HTTP GET request without a message body. The header of a request/response contains metadata, such as HTTP protocol version or content type.

var net = require('net'); var host = 'webcode.me'; var port = 80; var socket = new net.Socket(); socket.connect(port, host, () => < socket.write("HEAD / HTTP/1.0\r\n"); socket.write("Host: webcode.me\r\n"); socket.write("User-Agent: Node.js HTTP client\r\n"); socket.write("Accept: text/html\r\n"); socket.write("Accept-Language: en-US\r\n"); socket.write("Connection: close\r\n\r\n"); >); socket.on('data', (data) => < console.log(`$`); socket.destroy(); >);

A head request is issued with the HEAD command followed by the resource URL and HTTP protocol version. Note that the \r\n are mandatory part of the communication process. The details are described in RFC 7231 document.

client.on('data', (data) => < console.log(`$`); client.destroy(); >);
$ nodejs head_req.js HTTP/1.1 200 OK Server: nginx/1.6.2 Date: Wed, 10 Feb 2021 08:40:08 GMT Content-Type: text/html Content-Length: 348 Last-Modified: Sat, 20 Jul 2019 11:49:25 GMT Connection: close ETag: "5d32ffc5-15c" Accept-Ranges: bytes

JS socket GET request

The HTTP GET method requests a representation of the specified resource. Requests using GET should only retrieve data.

var net = require('net'); var host = 'webcode.me'; var port = 80; var socket = new net.Socket(); socket.connect(port, host, () => < socket.write('GET / HTTP/1.0\r\n\r\n'); >); socket.on('data', (data) => < console.log(`$`); socket.destroy(); >);

The example reads the home page of the webcode.me using a GET request. It returns its header and also its body.

socket.write('GET / HTTP/1.0\r\n\r\n');

We write the GET request to the socket.

$ nodejs get_req.js HTTP/1.1 200 OK Server: nginx/1.6.2 Date: Wed, 10 Feb 2021 08:45:01 GMT Content-Type: text/html Content-Length: 348 Last-Modified: Sat, 20 Jul 2019 11:49:25 GMT Connection: close ETag: "5d32ffc5-15c" Access-Control-Allow-Origin: * Accept-Ranges: bytes        

Today is a beautiful day. We go swimming and fishing.

Hello there. How are you?

JS socket QOTD

A quote of the day service is a useful debugging and measurement tool. The quote of the day service simply sends a short message without regard to the input. Port 17 is reserved for the quote of the day service.

var net = require('net'); var host = 'djxmmx.net'; var port = 17; var socket = new net.Socket(); socket.connect(port, host, function() < socket.write(''); >); socket.on('data', (data) => < console.log(`$`); socket.destroy(); >);

The example creates a client program that connects to a QOTD service.

We send an empty message to the socket.

socket.on('data', (data) => < console.log(`$`); socket.destroy(); >);

We receive the output and close the socket.

$ nodejs qotd.js "The secret of being miserable is to have leisure to bother about whether you are happy or not. The cure for it is occupation." George Bernard Shaw (1856-1950)

JS socket send mail

To send an email via socket, we utilize the SMTP commands, such as HELO, MAIL FROM, and DATA.

let net = require('net'); let host = '192.168.0.23'; let port = 25; let from = "john.doe@example.com"; let to = "root@core9"; let name = "John Doe"; let subject = "Hello"; let body = "Hello there"; let socket = new net.Socket(); socket.connect(port, host, () => < socket.write("HELO core9\n"); socket.write(`MAIL FROM: >\n`); socket.write(`RCPT TO: >\n`); socket.write("DATA\n"); socket.write(`From:$\n`); socket.write(`Subject:$\n`); socket.write(`$`); socket.write("\r\n.\r\n"); socket.write("QUIT\n"); >); socket.on('data', data => < console.log(`$`); >); socket.on('close', () => < socket.destroy(); >);

The example sends an email to a computer on a local network.

$ nodejs send_email.js 220 core9 ESMTP Sendmail 8.15.2/8.15.2; Thu, 11 Feb 2021 10:07:14 +0100 (CET) 250 core9 Hello spartan.local [192.168.0.20], pleased to meet you 250 2.1.0 . Sender ok 250 2.1.5 . Recipient ok 354 Enter mail, end with "." on a line by itself 250 2.0.0 11B97EKF001178 Message accepted for delivery 221 2.0.0 core9 closing connection
From john.doe@example.com Thu Feb 11 10:07:14 2021 Return-Path: Received: from core9 (spartan.local [192.168.0.20]) by core9 (8.15.2/8.15.2) with SMTP id 11B97EKF001178 for ; Thu, 11 Feb 2021 10:07:14 +0100 (CET) (envelope-from john.doe@example.com) Date: Thu, 11 Feb 2021 10:07:14 +0100 (CET) Message-Id: From:John.Doe Subject:Hello To: undisclosed-recipients:; Status: RO Hello there

We check the email on the receiving end.

JS socket echo server

An echo server is a simple server useful for testing. It simply sends the message back to the client.

var net = require('net'); var host = '0.0.0.0'; var port = 5050; net.createServer(sock => < console.log(`connected: $:$`); sock.on('data', (data) => < console.log(`$: $`); sock.write(`$`); >); sock.on('close', (data) => < console.log(`connection closed: $:$`); >); >).listen(port, host); console.log(`Server listening on $:$`);

A new server is created with the createServer function. The listen function start a server listening for connections.

$ nodejs echo_server.js Server listening on 0.0.0.0:5050
$ echo hello | nc localhost 5050 hello

With the nc tool, we send a message to the echo server.

In this article we have worked with sockets in JavaScript.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

Node.js v20.5.0 documentation

The node:net module provides an asynchronous network API for creating stream-based TCP or IPC servers ( net.createServer() ) and clients ( net.createConnection() ).

const net = require('node:net'); 

IPC support #

The node:net module supports IPC with named pipes on Windows, and Unix domain sockets on other operating systems.

Identifying paths for IPC connections #

On Unix, the local domain is also known as the Unix domain. The path is a file system pathname. It gets truncated to an OS-dependent length of sizeof(sockaddr_un.sun_path) — 1 . Typical values are 107 bytes on Linux and 103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket, it will unlink the Unix domain socket as well. For example, net.createServer() may create a Unix domain socket and server.close() will unlink it. But if a user creates the Unix domain socket outside of these abstractions, the user will need to remove it. The same applies when a Node.js API creates a Unix domain socket but the program then crashes. In short, a Unix domain socket will be visible in the file system and will persist until unlinked.

On Windows, the local domain is implemented using a named pipe. The path must refer to an entry in \\?\pipe\ or \\.\pipe\ . Any characters are permitted, but the latter may do some processing of pipe names, such as resolving .. sequences. Despite how it might look, the pipe namespace is flat. Pipes will not persist. They are removed when the last reference to them is closed. Unlike Unix domain sockets, Windows will close and remove the pipe when the owning process exits.

JavaScript string escaping requires paths to be specified with extra backslash escaping such as:

net.createServer().listen( path.join('\\\\?\\pipe', process.cwd(), 'myctl')); 

Class: net.BlockList #

The BlockList object can be used with some network APIs to specify rules for disabling inbound or outbound access to specific IP addresses, IP ranges, or IP subnets.

blockList.addAddress(address[, type]) #

Adds a rule to block the given IP address.

blockList.addRange(start, end[, type]) #

Adds a rule to block a range of IP addresses from start (inclusive) to end (inclusive).

blockList.addSubnet(net, prefix[, type]) #

Adds a rule to block a range of IP addresses specified as a subnet mask.

blockList.check(address[, type]) #

Returns true if the given IP address matches any of the rules added to the BlockList .

const blockList = new net.BlockList(); blockList.addAddress('123.123.123.123'); blockList.addRange('10.0.0.1', '10.0.0.10'); blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); console.log(blockList.check('123.123.123.123')); // Prints: true console.log(blockList.check('10.0.0.3')); // Prints: true console.log(blockList.check('222.111.111.222')); // Prints: false // IPv6 notation for IPv4 addresses works: console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true 

blockList.rules #

The list of rules added to the blocklist.

Источник

Читайте также:  Html css использование шрифтов
Оцените статью