Node js websocket error

Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js - ws/ws.md at master · websockets/ws

Table of Contents

  • Class: WebSocketServer
    • new WebSocketServer(options[, callback])
    • Event: ‘close’
    • Event: ‘connection’
    • Event: ‘error’
    • Event: ‘headers’
    • Event: ‘listening’
    • Event: ‘wsClientError’
    • server.address()
    • server.clients
    • server.close([callback])
    • server.handleUpgrade(request, socket, head, callback)
    • server.shouldHandle(request)
  • Class: WebSocket
    • Ready state constants
    • new WebSocket(address[, protocols][, options])
      • IPC connections
    • Event: ‘close’
    • Event: ‘error’
    • Event: ‘message’
    • Event: ‘open’
    • Event: ‘ping’
    • Event: ‘pong’
    • Event: ‘redirect’
    • Event: ‘unexpected-response’
    • Event: ‘upgrade’
    • websocket.addEventListener(type, listener[, options])
    • websocket.binaryType
    • websocket.bufferedAmount
    • websocket.close([code[, reason]])
    • websocket.extensions
    • websocket.isPaused
    • websocket.onclose
    • websocket.onerror
    • websocket.onmessage
    • websocket.onopen
    • websocket.pause()
    • websocket.ping([data[, mask]][, callback])
    • websocket.pong([data[, mask]][, callback])
    • websocket.protocol
    • websocket.readyState
    • websocket.removeEventListener(type, listener)
    • websocket.resume()
    • websocket.send(data[, options][, callback])
    • websocket.terminate()
    • websocket.url
  • createWebSocketStream(websocket[, options])
  • Environment variables
    • WS_NO_BUFFER_UTIL
    • WS_NO_UTF_8_VALIDATE
  • Error codes
    • WS_ERR_EXPECTED_FIN
    • WS_ERR_EXPECTED_MASK
    • WS_ERR_INVALID_CLOSE_CODE
    • WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH
    • WS_ERR_INVALID_OPCODE
    • WS_ERR_INVALID_UTF8
    • WS_ERR_UNEXPECTED_MASK
    • WS_ERR_UNEXPECTED_RSV_1
    • WS_ERR_UNEXPECTED_RSV_2_3
    • WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH
    • WS_ERR_UNSUPPORTED_MESSAGE_LENGTH

Class: WebSocketServer

This class represents a WebSocket server. It extends the EventEmitter.

new WebSocketServer(options[, callback])

  • options {Object}
    • backlog {Number} The maximum length of the queue of pending connections.
    • clientTracking {Boolean} Specifies whether or not to track clients.
    • handleProtocols {Function} A function which can be used to handle the
      WebSocket subprotocols. See description below.
    • host {String} The hostname where to bind the server.
    • maxPayload {Number} The maximum allowed message size in bytes. Defaults to
      100 MiB (104857600 bytes).
    • noServer {Boolean} Enable no server mode.
    • path {String} Accept only connections matching this path.
    • perMessageDeflate {Boolean|Object} Enable/disable permessage-deflate.
    • port {Number} The port where to bind the server.
    • server {http.Server|https.Server} A pre-created Node.js HTTP/S server.
    • skipUTF8Validation {Boolean} Specifies whether or not to skip UTF-8
      validation for text and close messages. Defaults to false. Set to true
      only if clients are trusted.
    • verifyClient {Function} A function which can be used to validate incoming
      connections. See description below. (Usage is discouraged: see
      Issue #337)
    • WebSocket {Function} Specifies the WebSocket class to be used. It must
      be extended from the original WebSocket. Defaults to WebSocket.
  • callback {Function}

Create a new server instance. One and only one of port, server or noServer
must be provided or an error is thrown. An HTTP server is automatically created,
started, and used if port is set. To use an external HTTP/S server instead,
specify only server or noServer. In this case the HTTP/S server must be
started manually. The «noServer» mode allows the WebSocket server to be
completely detached from the HTTP/S server. This makes it possible, for example,
to share a single HTTP/S server between multiple WebSocket servers.

NOTE: Use of verifyClient is discouraged. Rather handle client
authentication in the 'upgrade' event of the HTTP server. See examples for
more details.

If verifyClient is not set then the handshake is automatically accepted. If it
has a single parameter then ws will invoke it with the following argument:

  • info {Object}
    • origin {String} The value in the Origin header indicated by the client.
    • req {http.IncomingMessage} The client HTTP GET request.
    • secure {Boolean} true if req.socket.authorized or
      req.socket.encrypted is set.

The return value (Boolean) of the function determines whether or not to accept
the handshake.

If verifyClient has two parameters then ws will invoke it with the following
arguments:

  • info {Object} Same as above.
  • cb {Function} A callback that must be called by the user upon inspection of
    the info fields. Arguments in this callback are:

    • result {Boolean} Whether or not to accept the handshake.
    • code {Number} When result is false this field determines the HTTP
      error status code to be sent to the client.
    • name {String} When result is false this field determines the HTTP
      reason phrase.
    • headers {Object} When result is false this field determines additional
      HTTP headers to be sent to the client. For example,
      { 'Retry-After': 120 }.

handleProtocols takes two arguments:

  • protocols {Set} The list of WebSocket subprotocols indicated by the client
    in the Sec-WebSocket-Protocol header.
  • request {http.IncomingMessage} The client HTTP GET request.

The returned value sets the value of the Sec-WebSocket-Protocol header in the
HTTP 101 response. If returned value is false the header is not added in the
response.

If handleProtocols is not set then the first of the client’s requested
subprotocols is used.

perMessageDeflate can be used to control the behavior of permessage-deflate
extension. The extension is disabled when false (default
value). If an object is provided then that is extension parameters:

  • serverNoContextTakeover {Boolean} Whether to use context takeover or not.
  • clientNoContextTakeover {Boolean} Acknowledge disabling of client context
    takeover.
  • serverMaxWindowBits {Number} The value of windowBits.
  • clientMaxWindowBits {Number} Request a custom client window size.
  • zlibDeflateOptions {Object} Additional options to pass to
    zlib on deflate.
  • zlibInflateOptions {Object} Additional options to pass to
    zlib on inflate.
  • threshold {Number} Payloads smaller than this will not be compressed if
    context takeover is disabled. Defaults to 1024 bytes.
  • concurrencyLimit {Number} The number of concurrent calls to zlib. Calls
    above this limit will be queued. Default 10. You usually won’t need to touch
    this option. See this issue for more details.

If a property is empty then either an offered configuration or a default value
is used. When sending a fragmented message the length of the first fragment is
compared to the threshold. This determines if compression is used for the entire
message.

callback will be added as a listener for the 'listening' event on the HTTP
server when the port option is set.

Event: ‘close’

Emitted when the server closes. This event depends on the 'close' event of
HTTP server only when it is created internally. In all other cases, the event is
emitted independently.

Event: ‘connection’

  • websocket {WebSocket}
  • request {http.IncomingMessage}

Emitted when the handshake is complete. request is the http GET request sent
by the client. Useful for parsing authority headers, cookie headers, and other
information.

Event: ‘error’

  • error {Error}

Emitted when an error occurs on the underlying server.

Event: ‘headers’

  • headers {Array}
  • request {http.IncomingMessage}

Emitted before the response headers are written to the socket as part of the
handshake. This allows you to inspect/modify the headers before they are sent.

Event: ‘listening’

Emitted when the underlying server has been bound.

Event: ‘wsClientError’

  • error {Error}
  • socket {net.Socket|tls.Socket}
  • request {http.IncomingMessage}

Emitted when an error occurs before the WebSocket connection is established.
socket and request are respectively the socket and the HTTP request from
which the error originated. The listener of this event is responsible for
closing the socket. When the 'wsClientError' event is emitted there is no
http.ServerResponse object, so any HTTP response, including the response
headers and body, must be written directly to the socket. If there is no
listener for this event, the socket is closed with a default 4xx response
containing a descriptive error message.

server.address()

Returns an object with port, family, and address properties specifying the
bound address, the address family name, and port of the server as reported by
the operating system if listening on an IP socket. If the server is listening on
a pipe or UNIX domain socket, the name is returned as a string.

server.clients

  • {Set}

A set that stores all connected clients. This property is only added when the
clientTracking is truthy.

server.close([callback])

Prevent the server from accepting new connections and close the HTTP server if
created internally. If an external HTTP server is used via the server or
noServer constructor options, it must be closed manually. Existing connections
are not closed automatically. The server emits a 'close' event when all
connections are closed unless an external HTTP server is used and client
tracking is disabled. In this case the 'close' event is emitted in the next
tick. The optional callback is called when the 'close' event occurs and
receives an Error if the server is already closed.

server.handleUpgrade(request, socket, head, callback)

  • request {http.IncomingMessage} The client HTTP GET request.
  • socket {net.Socket|tls.Socket} The network socket between the server and
    client.
  • head {Buffer} The first packet of the upgraded stream.
  • callback {Function}.

Handle a HTTP upgrade request. When the HTTP server is created internally or
when the HTTP server is passed via the server option, this method is called
automatically. When operating in «noServer» mode, this method must be called
manually.

If the upgrade is successful, the callback is called with two arguments:

  • websocket {WebSocket} A WebSocket object.
  • request {http.IncomingMessage} The client HTTP GET request.

server.shouldHandle(request)

  • request {http.IncomingMessage} The client HTTP GET request.

See if a given request should be handled by this server. By default this method
validates the pathname of the request, matching it against the path option if
provided. The return value, true or false, determines whether or not to
accept the handshake.

This method can be overridden when a custom handling logic is required.

Class: WebSocket

This class represents a WebSocket. It extends the EventEmitter.

Ready state constants

Constant Value Description
CONNECTING 0 The connection is not yet open.
OPEN 1 The connection is open and ready to communicate.
CLOSING 2 The connection is in the process of closing.
CLOSED 3 The connection is closed.

new WebSocket(address[, protocols][, options])

  • address {String|url.URL} The URL to which to connect.
  • protocols {String|Array} The list of subprotocols.
  • options {Object}
    • followRedirects {Boolean} Whether or not to follow redirects. Defaults to
      false.
    • generateMask {Function} The function used to generate the masking key. It
      takes a Buffer that must be filled synchronously and is called before a
      message is sent, for each message. By default the buffer is filled with
      cryptographically strong random bytes.
    • handshakeTimeout {Number} Timeout in milliseconds for the handshake
      request. This is reset after every redirection.
    • maxPayload {Number} The maximum allowed message size in bytes. Defaults to
      100 MiB (104857600 bytes).
    • maxRedirects {Number} The maximum number of redirects allowed. Defaults
      to 10.
    • origin {String} Value of the Origin or Sec-WebSocket-Origin header
      depending on the protocolVersion.
    • perMessageDeflate {Boolean|Object} Enable/disable permessage-deflate.
    • protocolVersion {Number} Value of the Sec-WebSocket-Version header.
    • skipUTF8Validation {Boolean} Specifies whether or not to skip UTF-8
      validation for text and close messages. Defaults to false. Set to true
      only if the server is trusted.
    • Any other option allowed in http.request() or https.request().
      Options given do not have any effect if parsed from the URL given with the
      address parameter.

perMessageDeflate default value is true. When using an object, parameters
are the same of the server. The only difference is the direction of requests.
For example, serverNoContextTakeover can be used to ask the server to disable
context takeover.

Create a new WebSocket instance.

IPC connections

ws supports IPC connections. To connect to an IPC endpoint, use the following
URL form:

  • On Unices

    ws+unix:/absolute/path/to/uds_socket:/pathname?search_params
    
  • On Windows

    ws+unix:\.pipepipe_name:/pathname?search_params
    

The character : is the separator between the IPC path (the Unix domain socket
path or the Windows named pipe) and the URL path. The IPC path must not include
the characters : and ?, otherwise the URL is incorrectly parsed. If the URL
path is omitted

ws+unix:/absolute/path/to/uds_socket

it defaults to /.

Event: ‘close’

  • code {Number}
  • reason {Buffer}

Emitted when the connection is closed. code is a numeric value indicating the
status code explaining why the connection has been closed. reason is a
Buffer containing a human-readable string explaining why the connection has
been closed.

Event: ‘error’

  • error {Error}

Emitted when an error occurs. Errors may have a .code property, matching one
of the string values defined below under Error codes.

Event: ‘message’

  • data {Buffer|ArrayBuffer|Buffer[]}
  • isBinary {Boolean}

Emitted when a message is received. data is the message content. isBinary
specifies whether the message is binary or not.

Event: ‘open’

Emitted when the connection is established.

Event: ‘ping’

  • data {Buffer}

Emitted when a ping is received from the server.

Event: ‘pong’

  • data {Buffer}

Emitted when a pong is received from the server.

Event: ‘redirect’

  • url {String}
  • request {http.ClientRequest}

Emitted before a redirect is followed. url is the redirect URL. request is
the HTTP GET request with the headers queued. This event gives the ability to
inspect confidential headers and remove them on a per-redirect basis using the
request.getHeader() and request.removeHeader() API. The request
object should be used only for this purpose. When there is at least one listener
for this event, no header is removed by default, even if the redirect is to a
different domain.

Event: ‘unexpected-response’

  • request {http.ClientRequest}
  • response {http.IncomingMessage}

Emitted when the server response is not the expected one, for example a 401
response. This event gives the ability to read the response in order to extract
useful information. If the server sends an invalid response and there isn’t a
listener for this event, an error is emitted.

Event: ‘upgrade’

  • response {http.IncomingMessage}

Emitted when response headers are received from the server as part of the
handshake. This allows you to read headers from the server, for example
‘set-cookie’ headers.

websocket.addEventListener(type, listener[, options])

  • type {String} A string representing the event type to listen for.
  • listener {Function|Object} The listener to add.
  • options {Object}
    • once {Boolean} A Boolean indicating that the listener should be invoked
      at most once after being added. If true, the listener would be
      automatically removed when invoked.

Register an event listener emulating the EventTarget interface. This method
does nothing if type is not one of 'close', 'error', 'message', or
'open'.

websocket.binaryType

  • {String}

A string indicating the type of binary data being transmitted by the connection.
This should be one of «nodebuffer», «arraybuffer» or «fragments». Defaults to
«nodebuffer». Type «fragments» will emit the array of fragments as received from
the sender, without copyfull concatenation, which is useful for the performance
of binary protocols transferring large messages with multiple fragments.

websocket.bufferedAmount

  • {Number}

The number of bytes of data that have been queued using calls to send() but
not yet transmitted to the network. This deviates from the HTML standard in the
following ways:

  1. If the data is immediately sent the value is 0.
  2. All framing bytes are included.

websocket.close([code[, reason]])

  • code {Number} A numeric value indicating the status code explaining why the
    connection is being closed.
  • reason {String|Buffer} The reason why the connection is closing.

Initiate a closing handshake.

websocket.isPaused

  • {Boolean}

Indicates whether the websocket is paused.

websocket.extensions

  • {Object}

An object containing the negotiated extensions.

websocket.onclose

  • {Function}

An event listener to be called when connection is closed. The listener receives
a CloseEvent named «close».

websocket.onerror

  • {Function}

An event listener to be called when an error occurs. The listener receives an
ErrorEvent named «error».

websocket.onmessage

  • {Function}

An event listener to be called when a message is received from the server. The
listener receives a MessageEvent named «message».

websocket.onopen

  • {Function}

An event listener to be called when the connection is established. The listener
receives an OpenEvent named «open».

websocket.pause()

Pause the websocket causing it to stop emitting events. Some events can still be
emitted after this is called, until all buffered data is consumed. This method
is a noop if the ready state is CONNECTING or CLOSED.

websocket.ping([data[, mask]][, callback])

  • data {Array|Number|Object|String|ArrayBuffer|Buffer|DataView|TypedArray} The
    data to send in the ping frame.
  • mask {Boolean} Specifies whether data should be masked or not. Defaults to
    true when websocket is not a server client.
  • callback {Function} An optional callback which is invoked when the ping
    frame is written out. If an error occurs, the callback is called with the
    error as its first argument.

Send a ping. This method throws an error if the ready state is CONNECTING.

websocket.pong([data[, mask]][, callback])

  • data {Array|Number|Object|String|ArrayBuffer|Buffer|DataView|TypedArray} The
    data to send in the pong frame.
  • mask {Boolean} Specifies whether data should be masked or not. Defaults to
    true when websocket is not a server client.
  • callback {Function} An optional callback which is invoked when the pong
    frame is written out. If an error occurs, the callback is called with the
    error as its first argument.

Send a pong. This method throws an error if the ready state is CONNECTING.

websocket.protocol

  • {String}

The subprotocol selected by the server.

websocket.resume()

Make a paused socket resume emitting events. This method is a noop if the ready
state is CONNECTING or CLOSED.

websocket.readyState

  • {Number}

The current state of the connection. This is one of the ready state constants.

websocket.removeEventListener(type, listener)

  • type {String} A string representing the event type to remove.
  • listener {Function|Object} The listener to remove.

Removes an event listener emulating the EventTarget interface. This method
only removes listeners added with
websocket.addEventListener().

websocket.send(data[, options][, callback])

  • data {Array|Number|Object|String|ArrayBuffer|Buffer|DataView|TypedArray} The
    data to send. Object values are only supported if they conform to the
    requirements of Buffer.from(). If those constraints are not met, a
    TypeError is thrown.
  • options {Object}
    • binary {Boolean} Specifies whether data should be sent as a binary or
      not. Default is autodetected.
    • compress {Boolean} Specifies whether data should be compressed or not.
      Defaults to true when permessage-deflate is enabled.
    • fin {Boolean} Specifies whether data is the last fragment of a message
      or not. Defaults to true.
    • mask {Boolean} Specifies whether data should be masked or not. Defaults
      to true when websocket is not a server client.
  • callback {Function} An optional callback which is invoked when data is
    written out. If an error occurs, the callback is called with the error as its
    first argument.

Send data through the connection. This method throws an error if the ready
state is CONNECTING.

websocket.terminate()

Forcibly close the connection. Internally this calls socket.destroy().

websocket.url

  • {String}

The URL of the WebSocket server. Server clients don’t have this attribute.

createWebSocketStream(websocket[, options])

  • websocket {WebSocket} A WebSocket object.
  • options {Object} Options to pass to the Duplex
    constructor.

Returns a Duplex stream that allows to use the Node.js streams API on top of a
given WebSocket.

Environment variables

WS_NO_BUFFER_UTIL

When set to a non empty value, prevents the optional bufferutil dependency
from being required.

WS_NO_UTF_8_VALIDATE

When set to a non empty value, prevents the optional utf-8-validate dependency
from being required.

Error codes

Errors emitted by the websocket may have a .code property, describing the
specific type of error that has occurred:

WS_ERR_EXPECTED_FIN

A WebSocket frame was received with the FIN bit not set when it was expected.

WS_ERR_EXPECTED_MASK

An unmasked WebSocket frame was received by a WebSocket server.

WS_ERR_INVALID_CLOSE_CODE

A WebSocket close frame was received with an invalid close code.

WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH

A control frame with an invalid payload length was received.

WS_ERR_INVALID_OPCODE

A WebSocket frame was received with an invalid opcode.

WS_ERR_INVALID_UTF8

A text or close frame was received containing invalid UTF-8 data.

WS_ERR_UNEXPECTED_MASK

A masked WebSocket frame was received by a WebSocket client.

WS_ERR_UNEXPECTED_RSV_1

A WebSocket frame was received with the RSV1 bit set unexpectedly.

WS_ERR_UNEXPECTED_RSV_2_3

A WebSocket frame was received with the RSV2 or RSV3 bit set unexpectedly.

WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH

A data frame was received with a length longer than the max supported length
(2^53 — 1, due to JavaScript language limitations).

WS_ERR_UNSUPPORTED_MESSAGE_LENGTH

A message was received with a length longer than the maximum supported length,
as configured by the maxPayload option.

Node.js — это серверная платформа. Основная задача сервера — как можно быстрее и эффективнее обрабатывать запросы, поступающие от клиентов, в частности — от браузеров. Восьмая часть перевода руководства по Node.js, которую мы публикуем сегодня, посвящена протоколам HTTP и WebSocket.

[Советуем почитать] Другие части цикла

Часть 1: Общие сведения и начало работы
Часть 2: JavaScript, V8, некоторые приёмы разработки
Часть 3: Хостинг, REPL, работа с консолью, модули
Часть 4: npm, файлы package.json и package-lock.json
Часть 5: npm и npx
Часть 6: цикл событий, стек вызовов, таймеры
Часть 7: асинхронное программирование
Часть 8: Руководство по Node.js, часть 8: протоколы HTTP и WebSocket
Часть 9: Руководство по Node.js, часть 9: работа с файловой системой
Часть 10: Руководство по Node.js, часть 10: стандартные модули, потоки, базы данных, NODE_ENV
Полная PDF-версия руководства по Node.js

Что происходит при выполнении HTTP-запросов?

Поговорим о том, как браузеры выполняют запросы к серверам с использованием протокола HTTP/1.1.

Если вы когда-нибудь проходили собеседование в IT-сфере, то вас могли спросить о том, что происходит, когда вы вводите нечто в адресную строку браузера и нажимаете Enter. Пожалуй, это один из самых популярных вопросов, который встречается на подобных собеседованиях. Тот, кто задаёт подобные вопросы, хочет узнать, можете ли вы объяснить некоторые довольно-таки простые концепции и выяснить, понимаете ли вы принципы работы интернета.

Этот вопрос затрагивает множество технологий, понимать общие принципы которых — значит понимать, как устроена одна из самых сложных систем из когда-либо построенных человечеством, которая охватывает весь мир.

▍Протокол HTTP

Современные браузеры способны отличать настоящие URL-адреса, вводимые в их адресную строку, от поисковых запросов, для обработки которых обычно используется заданная по умолчанию поисковая система. Мы будем говорить именно об URL-адресах. Если вы введёте в строку браузера адрес сайта, вроде flaviocopes.com, браузер преобразует этот адрес к виду http://flaviocopes.com, исходя из предположения о том, что для обмена данными с указанным ресурсом будет использоваться протокол HTTP. Обратите внимание на то, что в Windows то, о чём мы будем тут говорить, может выглядеть немного иначе, чем в macOS и Linux.

▍Фаза DNS-поиска

Итак, браузер, начиная работу по загрузке данных с запрошенного пользователям адреса, выполняет операцию DNS-поиска (DNS Lookup) для того, чтобы выяснить IP-адрес соответствующего сервера. Символьные имена ресурсов, вводимые в адресную строку, удобны для людей, но устройство интернета подразумевает возможность обмена данными между компьютерами с использованием IP-адресов, которые представляют собой наборы чисел наподобие 222.324.3.1 (для протокола IPv4).

Сначала, выясняя IP-адрес сервера, браузер заглядывает в локальный DNS-кэш для того, чтобы узнать, не выполнялась ли недавно подобная процедура. В браузере Chrome, например, есть удобный способ посмотреть DNS-кэш, введя в адресной строке следующий адрес: chrome://net-internals/#dns.

Если в кэше ничего найти не удаётся, браузер использует системный вызов POSIX gethostbyname для того, чтобы узнать IP-адрес сервера.

▍Функция gethostbyname

Функция gethostbyname сначала проверяет файл hosts, который, в macOS или Linux, можно найти по адресу /etc/hosts, для того, чтобы узнать, можно ли, выясняя адрес сервера, обойтись локальными сведениями.

Если локальными средствами разрешить запрос на выяснение IP-адреса сервера не удаётся, система выполняет запрос к DNS-серверу. Адреса таких серверов хранятся в настройках системы.

Вот пара популярных DNS-серверов:

  • 8.8.8.8: DNS-сервер Google.
  • 1.1.1.1: DNS-сервер CloudFlare.

Большинство людей используют DNS-сервера, предоставляемые их провайдерами. Браузер выполняет DNS-запросы с использованием протокола UDP.

TCP и UDP — это два базовых протокола, применяемых в компьютерных сетях. Они расположены на одном концептуальном уровне, но TCP — это протокол, ориентированный на соединениях, а для обмена UDP-сообщениями, обработка которых создаёт небольшую дополнительную нагрузку на системы, процедура установления соединения не требуется. О том, как именно происходит обмен данными по UDP, мы говорить не будем.

IP-адрес, соответствующий интересующему нас доменному имени, может иметься в кэше DNS-сервера. Если это не так — он обратиться к корневому DNS-серверу. Система корневых DNS-серверов состоит из 13 серверов, от которых зависит работа всего интернета.

Надо отметить, что корневому DNS-серверу неизвестны соответствия между всеми существующими в мире доменными именами и IP-адресами. Но подобным серверам известны адреса DNS-серверов верхнего уровня для таких доменов, как .com, .it, .pizza, и так далее.

Получив запрос, корневой DNS-сервер перенаправляет его к DNS-серверу домена верхнего уровня, к так называемому TLD-серверу (от Top-Level Domain).

Предположим, браузер ищет IP-адрес для сервера flaviocopes.com. Обратившись к корневому DNS-серверу, браузер получит у него адрес TLD-сервера для зоны .com. Теперь этот адрес будет сохранён в кэше, в результате, если будет нужно узнать IP-адрес ещё какого-нибудь URL из зоны .com, к корневому DNS-серверу не придётся обращаться снова.

У TLD-серверов есть IP-адреса серверов имён (Name Server, NS), средствами которых и можно узнать IP-адрес по имеющемуся у нас URL. Откуда NS-сервера берут эти сведения? Дело в том, что если вы покупаете домен, доменный регистратор отправляет данные о нём серверам имён. Похожая процедура выполняется и, например, при смене хостинга.

Сервера, о которых идёт речь, обычно принадлежат хостинг-провайдерам. Как правило, для защиты от сбоев, создаются по несколько таких серверов. Например, у них могут быть такие адреса:

  • ns1.dreamhost.com
  • ns2.dreamhost.com
  • ns3.dreamhost.com

Для выяснения IP-адреса по URL, в итоге, обращаются к таким серверам. Именно они хранят актуальные данные об IP-адресах.

Теперь, после того, как нам удалось выяснить IP-адрес, стоящий за введённым в адресную строку браузера URL, мы переходим к следующему шагу нашей работы.

▍Установление TCP-соединения

Узнав IP-адрес сервера, клиент может инициировать процедуру TCP-подключения к нему. В процессе установления TCP-соединения клиент и сервер передают друг другу некоторые служебные данные, после чего они смогут обмениваться информацией. Это означает, что, после установления соединения, клиент сможет отправить серверу запрос.

▍Отправка запроса

Запрос представляет собой структурированный в соответствии с правилами используемого протокола фрагмент текста. Он состоит из трёх частей:

  • Строка запроса.
  • Заголовок запроса.
  • Тело запроса.

Строка запроса

Строка запроса представляет собой одну текстовую строку, в которой содержатся следующие сведения:

  • Метод HTTP.
  • Адрес ресурса.
  • Версия протокола.

Выглядеть она, например, может так:

GET / HTTP/1.1

Заголовок запроса

Заголовок запроса представлен набором пар вида поле: значение. Существуют 2 обязательных поля заголовка, одно из которых — Host, а второе — Connection. Остальные поля необязательны.

Заголовок может выглядеть так:

Host: flaviocopes.com
Connection: close

Поле Host указывает на доменное имя, которое интересует браузер. Поле Connection, установленное в значение close, означает, что соединение между клиентом и сервером не нужно держать открытым.

Среди других часто используемых заголовков запросов можно отметить следующие:

  • Origin
  • Accept
  • Accept-Encoding
  • Cookie
  • Cache-Control
  • Dnt

На самом деле, их существует гораздо больше.

Заголовок запроса завершается пустой строкой.

Тело запроса

Тело запроса необязательно, в GET-запросах оно не используется. Тело запроса используется в POST-запросах, а также в других запросах. Оно может содержать, например, данные в формате JSON.

Так как сейчас речь идёт о GET-запросе, тело запроса будет пустым, с ним мы работать не будем.

▍Ответ

После того, как сервер получает отправленный клиентом запрос, он его обрабатывает и отправляем клиенту ответ.

Ответ начинается с кода состояния и с соответствующего сообщения. Если запрос выполнен успешно, то начало ответа будет выглядеть так:

200 OK

Если что-то пошло не так, тут могут быть и другие коды. Например, следующие:

  • 404 Not Found
  • 403 Forbidden
  • 301 Moved Permanently
  • 500 Internal Server Error
  • 304 Not Modified
  • 401 Unauthorized

Далее в ответе содержится список HTTP-заголовков и тело ответа (которое, так как запрос выполняет браузер, будет представлять собой HTML-код).

Разбор HTML-кода

После того, как браузер получает ответ сервера, в теле которого содержится HTML-код, он начинает его разбирать, повторяя вышеописанный процесс для каждого ресурса, который нужен для формирования страницы. К таким ресурсам относятся, например, следующие:

  • CSS-файлы.
  • Изображения.
  • Значок веб-страницы (favicon).
  • JavaScript-файлы.

То, как именно браузер выводит страницу, к нашему разговору не относится. Главное, что нас тут интересует, заключается в том, что вышеописанный процесс запроса и получения данных используется не только для HTML-кода, но и для любых других объектов, передаваемых с сервера в браузер с использованием протокола HTTP.

О создании простого сервера средствами Node.js

Теперь, после того, как мы разобрали процесс взаимодействия браузера и сервера, вы можете по-новому взглянуть на раздел Первое Node.js-приложение из первой части этой серии материалов, в котором мы описывали код простого сервера.

Выполнение HTTP-запросов средствами Node.js

Для выполнения HTTP-запросов средствами Node.js используется соответствующий модуль. В приведённых ниже примерах применяется модуль https. Дело в том, что в современных условиях всегда, когда это возможно, нужно применять именно протокол HTTPS.

▍Выполнение GET-запросов

Вот пример выполнения GET-запроса средствами Node.js:

const https = require('https')
const options = {
  hostname: 'flaviocopes.com',
  port: 443,
  path: '/todos',
  method: 'GET'
}
const req = https.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`)
  res.on('data', (d) => {
    process.stdout.write(d)
  })
})
req.on('error', (error) => {
  console.error(error)
})
req.end()

▍Выполнение POST-запроса

Вот как выполнить POST-запрос из Node.js:

const https = require('https')
const data = JSON.stringify({
  todo: 'Buy the milk'
})
const options = {
  hostname: 'flaviocopes.com',
  port: 443,
  path: '/todos',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
}
const req = https.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`)
  res.on('data', (d) => {
    process.stdout.write(d)
  })
})
req.on('error', (error) => {
  console.error(error)
})
req.write(data)
req.end()

▍Выполнение PUT-запросов и DELETE-запросов

Выполнение таких запросов выглядит так же, как и выполнение POST-запросов. Главное отличие, помимо смыслового наполнения таких операций, заключается в значении свойства method объекта options.

▍Выполнение HTTP-запросов в Node.js с использованием библиотеки Axios

Axios — это весьма популярная JavaScript-библиотека, работающая и в браузере (сюда входят все современные браузеры и IE, начиная с IE8), и в среде Node.js, которую можно использовать для выполнения HTTP-запросов.

Эта библиотека основана на промисах, она обладает некоторыми преимуществами перед стандартными механизмами, в частности, перед API Fetch. Среди её преимуществ можно отметить следующие:

  • Поддержка старых браузеров (для использования Fetch нужен полифилл).
  • Возможность прерывания запросов.
  • Поддержка установки тайм-аутов для запросов.
  • Встроенная защита от CSRF-атак.
  • Поддержка выгрузки данных с предоставлением сведений о ходе этого процесса.
  • Поддержка преобразования JSON-данных.
  • Работа в Node.js

Установка

Для установки Axios можно воспользоваться npm:

npm install axios

Того же эффекта можно достичь и при работе с yarn:

yarn add axios

Подключить библиотеку к странице можно с помощью unpkg.com:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

API Axios

Выполнить HTTP-запрос можно, воспользовавшись объектом axios:

axios({
  url: 'https://dog.ceo/api/breeds/list/all',
  method: 'get',
  data: {
    foo: 'bar'
  }
})

Но обычно удобнее пользоваться специальными методами:

  • axios.get()
  • axios.post()

Это похоже на то, как в jQuery, вместо $.ajax() пользуются $.get() и $.post().

Axios предлагает отдельные методы и для выполнения других видов HTTP-запросов, которые не так популярны, как GET и POST, но всё-таки используются:

  • axios.delete()
  • axios.put()
  • axios.patch()
  • axios.options()

В библиотеке имеется метод для выполнения запроса, предназначенного для получения лишь HTTP-заголовков, без тела ответа:

  • axios.head()

Запросы GET

Axios удобно использовать с применением современного синтаксиса async/await. В следующем примере кода, рассчитанном на Node.js, библиотека используется для загрузки списка пород собак из API Dog. Здесь применяется метод axios.get() и осуществляется подсчёт пород:

const axios = require('axios')
const getBreeds = async () => {
  try {
    return await axios.get('https://dog.ceo/api/breeds/list/all')
  } catch (error) {
    console.error(error)
  }
}
const countBreeds = async () => {
  const breeds = await getBreeds()
  if (breeds.data.message) {
    console.log(`Got ${Object.entries(breeds.data.message).length} breeds`)
  }
}
countBreeds()

То же самое можно переписать и без использования async/await, применив промисы:

const axios = require('axios')
const getBreeds = () => {
  try {
    return axios.get('https://dog.ceo/api/breeds/list/all')
  } catch (error) {
    console.error(error)
  }
}
const countBreeds = async () => {
  const breeds = getBreeds()
    .then(response => {
      if (response.data.message) {
        console.log(
          `Got ${Object.entries(response.data.message).length} breeds`
        )
      }
    })
    .catch(error => {
      console.log(error)
    })
}
countBreeds()

Использование параметров в GET-запросах

GET-запрос может содержать параметры, которые в URL выглядят так:

https://site.com/?foo=bar

При использовании Axios запрос подобного рода можно выполнить так:

axios.get('https://site.com/?foo=bar')

Того же эффекта можно достичь, настроив свойство params в объекте с параметрами:

axios.get('https://site.com/', {
  params: {
    foo: 'bar'
  }
})

Запросы POST

Выполнение POST-запросов очень похоже на выполнение GET-запросов, но тут, вместо метода axios.get(), используется метод axios.post():

axios.post('https://site.com/')

В качестве второго аргумента метод post принимает объект с параметрами запроса:

axios.post('https://site.com/', {
  foo: 'bar'
})

Использование протокола WebSocket в Node.js

WebSocket представляет собой альтернативу HTTP, его можно применять для организации обмена данными в веб-приложениях. Этот протокол позволяет создавать долгоживущие двунаправленные каналы связи между клиентом и сервером. После установления соединения канал связи остаётся открытым, что даёт в распоряжение приложения очень быстрое соединение, характеризующееся низкими задержками и небольшой дополнительной нагрузкой на систему.

Протокол WebSocket поддерживают все современные браузеры.

▍Отличия от HTTP

HTTP и WebSocket — это очень разные протоколы, в которых используются различные подходы к обмену данными. HTTP основан на модели «запрос — ответ»: сервер отправляет клиенту некие данные после того, как они будут запрошены. В случае с WebSocket всё устроено иначе. А именно:

  • Сервер может отправлять сообщения клиенту по своей инициативе, не дожидаясь поступления запроса от клиента.
  • Клиент и сервер могут обмениваться данными одновременно.
  • При передаче сообщения используется крайне малый объём служебных данных. Это, в частности, ведёт к низким задержкам при передаче данных.

Протокол WebSocket очень хорошо подходит для организации связи в режиме реального времени по каналам, которые долго остаются открытыми. HTTP, в свою очередь, отлично подходит для организации эпизодических сеансов связи, инициируемых клиентом. В то же время надо отметить, что, с точки зрения программирования, реализовать обмен данными по протоколу HTTP гораздо проще, чем по протоколу WebSocket.

▍Защищённая версия протокола WebSocket

Существует небезопасная версия протокола WebSocket (URI-схема ws://), которая напоминает, в плане защищённости, протокол http://. Использования ws:// следует избегать, отдавая предпочтение защищённой версии протокола — wss://.

▍Создание WebSocket-соединения

Для создания WebSocket-соединения нужно воспользоваться соответствующим конструктором:

const url = 'wss://myserver.com/something'
const connection = new WebSocket(url)

После успешного установления соединения вызывается событие open. Организовать прослушивание этого события можно, назначив функцию обратного вызова свойству onopen объекта connection:

connection.onopen = () => {
  //...

}

Для обработки ошибок используется обработчик события onerror:

connection.onerror = error => {
  console.log(`WebSocket error: ${error}`)
}

▍Отправка данных на сервер

После открытия WebSocket-соединения с сервером ему можно отправлять данные. Сделать это можно, например в коллбэке onopen:

connection.onopen = () => {
  connection.send('hey')
}

▍Получение данных с сервера

Для получения с сервера данных, отправленных с использованием протокола WebSocket, можно назначить коллбэк onmessage, который будет вызван при получении события message:

connection.onmessage = e => {
  console.log(e.data)
}

▍Реализация WebSocket-сервера в среде Node.js

Для того чтобы реализовать WebSocket-сервер в среде Node.js, можно воспользоваться популярной библиотекой ws. Мы применим её для разработки сервера, но она подходит и для создания клиентов, и для организации взаимодействия между двумя серверами.

Установим эту библиотеку, предварительно инициализировав проект:

yarn init
yarn add ws

Код WebSocket-сервера, который нам надо написать, довольно-таки компактен:

constWebSocket = require('ws')
const wss = newWebSocket.Server({ port: 8080 })
wss.on('connection', ws => {
  ws.on('message', message => {
    console.log(`Received message => ${message}`)
  })
  ws.send('ho!')
})

Здесь мы создаём новый сервер, который прослушивает стандартный для протокола WebSocket порт 8080 и описываем коллбэк, который, когда будет установлено соединение, отправляет клиенту сообщение ho! и выводит в консоль сообщение, полученное от клиента.

Вот рабочий пример WebSocket-сервера, а вот — клиент, который может с ним взаимодействовать.

Итоги

Сегодня мы поговорили о механизмах сетевого взаимодействия, поддерживаемых платформой Node.js, проведя параллели с аналогичными механизмами, применяемыми в браузерах. Нашей следующей темой будет работа с файлами.

Уважаемые читатели! Пользуетесь ли вы протоколом WebSocket в своих веб-приложениях, серверная часть которых создана средствами Node.js?

WebSocket — это протокол передачи данных, основанный на протоколе TCP обеспечивающий обмен сообщениями между клиентом и сервером в режиме реального времени.

Протокол WebSocket¶

Для установления соединения по WebSocket клиентская сторона сперва отправляет используя протокол HTTP специальные заголовки Upgrade и Connection, тем самым говоря, что она хочет перейти на общение по WebSocket. А сервер уже сам решает, разрешать установку соединения или нет.

Обмен сообщениями между сервером и клиентом осуществляется с помощью специальных пакетов, называемых фреймами. Выделяют два типа фреймов:

  • Управляющие данными (посылают данные);
  • Управляющие соединением (проверяют установку соединения через PING или закрывают его).

Node.js и socket.io¶

Для использования в Node.js WebSocket необходимо установить npm модуль socket.io.

npm install socket.io --save

Рассмотрим пример.

app.js

const express = require('express'),
  app = express(),
  http = require('http').createServer(app),
  io = require('socket.io')(http)

const host = '127.0.0.1'
const port = 7000

let clients = []

io.on('connection', (socket) => {
  console.log(`Client with id ${socket.id} connected`)
  clients.push(socket.id)

  socket.emit('message', "I'm server")

  socket.on('message', (message) =>
    console.log('Message: ', message)
  )

  socket.on('disconnect', () => {
    clients.splice(clients.indexOf(socket.id), 1)
    console.log(`Client with id ${socket.id} disconnected`)
  })
})

app.use(express.static(__dirname))

app.get('/', (req, res) => res.render('index'))

//получение количества активных клиентов
app.get('/clients-count', (req, res) => {
  res.json({
    count: io.clients().server.engine.clientsCount,
  })
})

//отправка сообщения конкретному клиенту по его id
app.post('/client/:id', (req, res) => {
  if (clients.indexOf(req.params.id) !== -1) {
    io.sockets.connected[req.params.id].emit(
      'private message',
      `Message to client with id ${req.params.id}`
    )
    return res
      .status(200)
      .json({
        message: `Message was sent to client with id ${req.params.id}`,
      })
  } else
    return res
      .status(404)
      .json({ message: 'Client not found' })
})

http.listen(port, host, () =>
  console.log(`Server listens http://${host}:${port}`)
)

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Socket.io example</title>
    <script src="/node_modules/socket.io-client/dist/socket.io.js"></script>
    <script>
      let socket = io()

      socket.on('message', (message) =>
        console.log('Message from server: ', message)
      )
      socket.on('private message', (message) =>
        console.log(
          'Private message from server: ',
          message
        )
      )

      function sendMessageToServer() {
        socket.emit('message', "I'm client")
      }
    </script>
  </head>
  <body>
    <button onclick="sendMessageToServer()">
      Send message to server
    </button>
  </body>
</html>

Для подключения WebSocket на клиентской стороне используется модуль socket.io-client, экземпляру которого передается адрес сервера, с которым необходимо установить соединение по WebSocket.

При установке соединения между клиентом и сервером Node.js по WebSocket генерируется событие connection, которое обрабатывается с помощью метода on() модуля socket.io. Передаваемая вторым параметром методу on() callback-функция единственным параметром принимает экземпляр соединения (далее просто сокет).

io.on('connection', (socket) => {})

Каждое соединение имеет свой уникальный идентификатор, зная который можно отправить сообщение конкретному клиенту (см. в примере маршрут /client/:id).

При разрыве соединения генерируется событие disconnect. Соединение разрывается, когда пользователь закрывает вкладку или когда сервер вызывает у сокета метод disconnect().

socket.on('disconnect', () => {})

Для отправки данных от сервера Node.js к клиенту (и наоборот), используется метод emit(), которые принимает следующие параметры:

  • имя события;
  • данные, которые необходимо отправить (могут быть отправлены в виде REST-аргументов);
  • callback-функция (передается последним параметром), которая будет вызвана, когда вторая сторона получит сообщение.

Обработка отправляемых данных на стороне получателя происходит с использованием уже знакомого метода on(), первым параметром принимающего имя события, указанного в emit(), вторым — callback-функцию с переданными данными в качестве ее параметров.

//получатель
let socket = io()

socket.on('message', (message) =>
  console.log('Message from server: ', message)
)

//отправитель
io.on('connection', (socket) => {
  socket.emit('message', "I'm server")
})

Для отправки данных всем клиентам, используйте метод emit() применительно к объекту io.sockets.

io.sockets.emit('message', 'Message for all clients')

Чтобы узнать текущее количество соединений, используйте метод clients(), вызываемый применительно к свойству sockets экземпляра модуля socket.io (см. в примере маршрут /clients-count).

В качестве необязательного параметра методу clients() можно передать имя «комнаты», количество соединений для который вы хотите узнать.

Пространства и «комнаты»¶

В протоколе WebSocket существуют такие понятия, как пространства и «комнаты». По умолчанию посылаемые данные отправляются всем сокетам, но принимают эти данные лишь некоторые из них. Получается, что в определенные моменты времени будет установлено избыточное количество соединений. Чтобы избежать этого, используйте пространства.

Пространства позволяют изолировать одни сокеты от других.

app.js

const express = require('express'),
  app = express(),
  http = require('http').createServer(app),
  io = require('socket.io')(http)

const host = '127.0.0.1'
const port = 7000

const nmspc1 = io.of('/your-namespace1')
const nmspc2 = io.of('/your-namespace2')

nmspc1.on('connection', (socket) => {
  console.log(
    `Client ${socket.id} connected to /your-namespace1`
  )
})

nmspc2.on('connection', (socket) => {
  console.log(
    `Client ${socket.id} connected to /your-namespace2`
  )
})

app.use(express.static(__dirname))

app.get('/', (req, res) => res.render('index'))

http.listen(port, host, () =>
  console.log(`Server listens http://${host}:${port}`)
)
let socket = io('/your-namespace1')

В приведенном примере с помощью метода of() на сервере определяются два пространства: /users и /orders. На клиентской стороне подключение к тому или иному пространству происходит в зависимости от текущего маршрута. Таким образом, при отправке данных, например, из пространства /users, об этом будут оповещены только сокеты этого пространства. По умолчанию все сокеты находятся в пространстве /.

Также и в пределах пространства можно распределять сокеты по так называемым «комнатам».

io.on('connection', (socket) => {
  socket.join('Room №1')
})

Чтобы отнести сокет к определенной «комнате» используется метод пространства join(), который принимает имя «комнаты» (задается пользователем модуля socket.io). Для вынесения сокета из комнаты используйте метод leave().

Отправка данных в «комнату» осуществляется с помощью метода to().

io.to('Room №1').emit('message', 'Message form Room №1')

Обработка инициируемых в пределах «комнаты» событий осуществляется с использованием метода in().

io.in('Room №1').on('message', (message) =>
  console.log('Room №1. Message: ', message)
)

So I am trying to set up a website that also has websockets where both the http-server and the websocket listens on the same port:

const WebSocket = require('ws');
var express = require('express');
var app = express();

wss = new WebSocket.Server({server : app});

app.get('/', function(req, res){

res.send('hello world!');
});

wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});

ws.send('some text');
});

app.listen(8080, function(){

console.log('app started');
});

If I then load the servers website in chrome-browser I am greeted with «hello world!». So far so good. But if I open up the webconsole and try to connect with

var exampleSocket = new WebSocket("ws://192.10.10.30:8080");

I get the following errormessage:

WebSocket connection to ‘ws://192.10.10.30:8080/’ failed: Error
during WebSocket handshake: Unexpected response code: 200

My first thought was, do I have to explicitly declare an http-server ?

But I read this post
Serve WebSocket and HTTP server at same address on Node.js and there was no http-server explicitly declared. Please help me on this.

javascript node.js express websocket

asked Nov 26 ’18 at 16:54

So I am trying to set up a website that also has websockets where both the http-server and the websocket listens on the same port:

const WebSocket = require('ws');
var express = require('express');
var app = express();

wss = new WebSocket.Server({server : app});

app.get('/', function(req, res){

res.send('hello world!');
});

wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});

ws.send('some text');
});

app.listen(8080, function(){

console.log('app started');
});

If I then load the servers website in chrome-browser I am greeted with «hello world!». So far so good. But if I open up the webconsole and try to connect with

var exampleSocket = new WebSocket("ws://192.10.10.30:8080");

I get the following errormessage:

WebSocket connection to ‘ws://192.10.10.30:8080/’ failed: Error
during WebSocket handshake: Unexpected response code: 200

My first thought was, do I have to explicitly declare an http-server ?

But I read this post
Serve WebSocket and HTTP server at same address on Node.js and there was no http-server explicitly declared. Please help me on this.

javascript node.js express websocket

asked Nov 26 ’18 at 16:54

1

So I am trying to set up a website that also has websockets where both the http-server and the websocket listens on the same port:

const WebSocket = require('ws');
var express = require('express');
var app = express();

wss = new WebSocket.Server({server : app});

app.get('/', function(req, res){

res.send('hello world!');
});

wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});

ws.send('some text');
});

app.listen(8080, function(){

console.log('app started');
});

If I then load the servers website in chrome-browser I am greeted with «hello world!». So far so good. But if I open up the webconsole and try to connect with

var exampleSocket = new WebSocket("ws://192.10.10.30:8080");

I get the following errormessage:

WebSocket connection to ‘ws://192.10.10.30:8080/’ failed: Error
during WebSocket handshake: Unexpected response code: 200

My first thought was, do I have to explicitly declare an http-server ?

But I read this post
Serve WebSocket and HTTP server at same address on Node.js and there was no http-server explicitly declared. Please help me on this.

javascript node.js express websocket

asked Nov 26 ’18 at 16:54

So I am trying to set up a website that also has websockets where both the http-server and the websocket listens on the same port:

const WebSocket = require('ws');
var express = require('express');
var app = express();

wss = new WebSocket.Server({server : app});

app.get('/', function(req, res){

res.send('hello world!');
});

wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});

ws.send('some text');
});

app.listen(8080, function(){

console.log('app started');
});

If I then load the servers website in chrome-browser I am greeted with «hello world!». So far so good. But if I open up the webconsole and try to connect with

var exampleSocket = new WebSocket("ws://192.10.10.30:8080");

I get the following errormessage:

WebSocket connection to ‘ws://192.10.10.30:8080/’ failed: Error
during WebSocket handshake: Unexpected response code: 200

My first thought was, do I have to explicitly declare an http-server ?

But I read this post
Serve WebSocket and HTTP server at same address on Node.js and there was no http-server explicitly declared. Please help me on this.

javascript node.js express websocket

javascript node.js express websocket

asked Nov 26 ’18 at 16:54

asked Nov 26 ’18 at 16:54

asked Nov 26 ’18 at 16:54

asked Nov 26 ’18 at 16:54

asked Nov 26 ’18 at 16:54

You’re passing an Express app instance as server, which should be an HTTP/HTTPS server instance. Such an instance is returned by app.listen:

var app = express();
var server = app.listen(8080, function(){
console.log('app started');
});

wss = new WebSocket.Server({server : server});

answered Nov 26 ’18 at 20:03

Your Answer

StackExchange.ifUsing(«editor», function () {
StackExchange.using(«externalEditor», function () {
StackExchange.using(«snippets», function () {
StackExchange.snippets.init();
});
});
}, «code-snippets»);

StackExchange.ready(function() {
var channelOptions = {
tags: «».split(» «),
id: «1»
};
initTagRenderer(«».split(» «), «».split(» «), channelOptions);

StackExchange.using(«externalEditor», function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using(«snippets», function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: ‘answer’,
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: «»,
imageUploader: {
brandingHtml: «Powered by u003ca class=»icon-imgur-white» href=»https://imgur.com/»u003eu003c/au003e»,
contentPolicyHtml: «User contributions licensed under u003ca href=»https://creativecommons.org/licenses/by-sa/3.0/»u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href=»https://stackoverflow.com/legal/content-policy»u003e(content policy)u003c/au003e»,
allowUrls: true
},
onDemand: true,
discardSelector: «.discard-answer»
,immediatelyShowMarkdownHelp:true
});

}
});

Sign up or log in

StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave(‘#login-link’);
});

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

StackExchange.ready(
function () {
StackExchange.openid.initPostLogin(‘.new-post-login’, ‘https%3a%2f%2fstackoverflow.com%2fquestions%2f53485713%2fnode-js-with-express-and-websocket-giving-error-during-websocket-handshake-unex%23new-answer’, ‘question_page’);
}
);

Post as a guest

Email

Required, but never shown

You’re passing an Express app instance as server, which should be an HTTP/HTTPS server instance. Such an instance is returned by app.listen:

var app = express();
var server = app.listen(8080, function(){
console.log('app started');
});

wss = new WebSocket.Server({server : server});

answered Nov 26 ’18 at 20:03

You’re passing an Express app instance as server, which should be an HTTP/HTTPS server instance. Such an instance is returned by app.listen:

var app = express();
var server = app.listen(8080, function(){
console.log('app started');
});

wss = new WebSocket.Server({server : server});

answered Nov 26 ’18 at 20:03

0

You’re passing an Express app instance as server, which should be an HTTP/HTTPS server instance. Such an instance is returned by app.listen:

var app = express();
var server = app.listen(8080, function(){
console.log('app started');
});

wss = new WebSocket.Server({server : server});

answered Nov 26 ’18 at 20:03

You’re passing an Express app instance as server, which should be an HTTP/HTTPS server instance. Such an instance is returned by app.listen:

var app = express();
var server = app.listen(8080, function(){
console.log('app started');
});

wss = new WebSocket.Server({server : server});

answered Nov 26 ’18 at 20:03

answered Nov 26 ’18 at 20:03

answered Nov 26 ’18 at 20:03

answered Nov 26 ’18 at 20:03

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Sign up or log in

StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave(‘#login-link’);
});

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

StackExchange.ready(
function () {
StackExchange.openid.initPostLogin(‘.new-post-login’, ‘https%3a%2f%2fstackoverflow.com%2fquestions%2f53485713%2fnode-js-with-express-and-websocket-giving-error-during-websocket-handshake-unex%23new-answer’, ‘question_page’);
}
);

Post as a guest

Email

Required, but never shown

Sign up or log in

StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave(‘#login-link’);
});

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

Sign up or log in

StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave(‘#login-link’);
});

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

Sign up or log in

StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave(‘#login-link’);
});

Sign up using Email and Password

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Node js validation error
  • Node js try catch error
  • Node js throw new error
  • Node js route error
  • Node js pipe error

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии