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.

Читайте также:  Relative and absolute paths php

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.

Читайте также:  Создание своих аннотаций java

Источник

The Socket instance (client-side)

A Socket is the fundamental class for interacting with the server. It inherits most of the methods of the Node.js EventEmitter, like emit, on, once or off.

Bidirectional communication between server and clientBidirectional communication between server and client

Besides emitting and listening to events, the Socket instance has a few attributes that may be of use in your application:

Socket#id​

Each new connection is assigned a random 20-characters identifier.

This identifier is synced with the value on the server-side.

// server-side io.on("connection", (socket) =>   console.log(socket.id); // x8WIv7-mJelg7on_ALbx >);  // client-side socket.on("connect", () =>   console.log(socket.id); // x8WIv7-mJelg7on_ALbx >); socket.on("disconnect", () =>   console.log(socket.id); // undefined >); 

Please note that, unless connection state recovery is enabled, the id attribute is an ephemeral ID that is not meant to be used in your application (or only for debugging purposes) because:

  • this ID is regenerated after each reconnection (for example when the WebSocket connection is severed, or when the user refreshes the page)
  • two different browser tabs will have two different IDs
  • there is no message queue stored for a given ID on the server (i.e. if the client is disconnected, the messages sent from the server to this ID are lost)

Please use a regular session ID instead (either sent in a cookie, or stored in the localStorage and sent in the auth payload).

Socket#connected​

This attribute describes whether the socket is currently connected to the server.

socket.on("connect", () =>   console.log(socket.connected); // true >); socket.on("disconnect", () =>   console.log(socket.connected); // false >); 

Socket#io​

A reference to the underlying Manager.

socket.on("connect", () =>   const engine = socket.io.engine; console.log(engine.transport.name); // in most cases, prints "polling"  engine.once("upgrade", () =>   // called when the transport is upgraded (i.e. from HTTP long-polling to WebSocket) console.log(engine.transport.name); // in most cases, prints "websocket" >);  engine.on("packet", ( type, data >) =>   // called for each packet received >);  engine.on("packetCreate", ( type, data >) =>   // called for each packet sent >);  engine.on("drain", () =>   // called when the write buffer is drained >);  engine.on("close", (reason) =>   // called when the underlying connection is closed >); >); 

Lifecycle​

Lifecycle diagramLifecycle diagram

Events​

The Socket instance emits three special events:

Please note that since Socket.IO v3, the Socket instance does not emit any event related to the reconnection logic anymore. You can listen to the events on the Manager instance directly:

socket.io.on("reconnect_attempt", () =>   // . >); socket.io.on("reconnect", () =>   // . >); 

More information can be found in the migration guide.

connect ​

This event is fired by the Socket instance upon connection and reconnection.

Please note that you shouldn’t register event handlers in the connect handler itself, as a new handler will be registered every time the Socket reconnects:

// BAD socket.on("connect", () =>   socket.on("data", () =>  /* . */ >); >);  // GOOD socket.on("connect", () =>   // . >); socket.on("data", () =>  /* . */ >); 

connect_error ​

  • the low-level connection cannot be established
  • the connection is denied by the server in a middleware function

In the first case, the Socket will automatically try to reconnect, after a given delay.

In the latter case, you need to manually reconnect. You might need to update the credentials:

// either by directly modifying the `auth` attribute socket.on("connect_error", () =>   socket.auth.token = "abcd";  socket.connect(); >);  // or if the `auth` attribute is a function const socket = io(  auth: (cb) =>   cb(localStorage.getItem("token")); > >); socket.on("connect_error", () =>   setTimeout(() =>   socket.connect(); >, 1000); >); 

disconnect ​

This event is fired upon disconnection.

socket.on("disconnect", (reason) =>   // . >); 

Here is the list of possible reasons:

Reason Description
io server disconnect The server has forcefully disconnected the socket with socket.disconnect()
io client disconnect The socket was manually disconnected using socket.disconnect()
ping timeout The server did not send a PING within the pingInterval + pingTimeout range
transport close The connection was closed (example: the user has lost connection, or the network was changed from WiFi to 4G)
transport error The connection has encountered an error (example: the server was killed during a HTTP long-polling cycle)

In the first two cases (explicit disconnection), the client will not try to reconnect and you need to manually call socket.connect() .

In all other cases, the client will wait for a small random delay and then try to reconnect:

socket.on("disconnect", (reason) =>   if (reason === "io server disconnect")   // the disconnection was initiated by the server, you need to reconnect manually  socket.connect(); > // else the socket will automatically try to reconnect >); 

Note: those events, along with disconnecting , newListener and removeListener , are special events that shouldn’t be used in your application:

// BAD, will throw an error socket.emit("disconnect"); 

Complete API​

The complete API exposed by the Socket instance can be found here.

Источник

Оцените статью