热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Node.jsHTTP2服务器错误:套接字挂断-Node.jsHTTP2serverError:sockethangup

GiventhelatestversionofNode.jswithexperimentalHTTP2support:鉴于最新版本的Node.js具有实验性HTTP2支持:$

Given the latest version of Node.js with experimental HTTP2 support:

鉴于最新版本的Node.js具有实验性HTTP2支持:

$ node -v
v9.2.0

An HTTP2 server:

HTTP2服务器:

var optiOns= {
  key: getKey(),
  cert: getCert(),
  allowHTTP1: true
}

var server = http2.createSecureServer(options)
server.on('stream', onstream)
server.on('error', onerror)
server.on('connect', onconnect)
server.on('socketError', onsocketerror)
server.on('frameError', onframeerror)
server.on('remoteSettings', onremotesettings)
server.listen(8443)

function onconnect() {
  console.log('connect')
}

function onremotesettings(settings) {
  console.log('remote settings', settings)
}

function onframeerror(error) {
  console.log('frame error', error)
}

function onsocketerror(error) {
  console.log('socket error', error)
}

function onerror(error) {
  console.log(error)
}

function onstream(stream, headers) {
  console.log('stream')
}

And a request made to it:

并向它提出了一个要求:

var https = require('https')

var optiOns= {
  method: 'GET',
  hostname: 'localhost',
  port: '8443',
  path: '/',
  protocol: 'https:',
  rejectUnauthorized: false,
  agent: false
}

var req = https.request(options, function(res){
  var body = ''
  res.setEncoding('utf8')
  res.on('data', function(data){
    body += data;
  });
  res.on('end', function(){
    callback(null, body)
  })
})

req.end()

It just hangs and eventually says:

它只是挂起并最终说:

Error: socket hang up
at createHangUpError (_http_client.js:330:15)
    at TLSSocket.socketOnEnd (_http_client.js:423:23)
    at TLSSocket.emit (events.js:164:20)
    at endReadableNT (_stream_readable.js:1054:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)

If rejectUnauthorized: true is set, then it errors:

如果设置了rejectUnauthorized:true,则会出错:

Error: self signed certificate
    at TLSSocket.onConnectSecure (_tls_wrap.js:1036:34)
    at TLSSocket.emit (events.js:159:13)
    at TLSSocket._finishInit (_tls_wrap.js:637:8)

Not sure what is going wrong and why it won't get to the point of logging stream.

不确定出了什么问题以及为什么它不会达到记录流的目的。

If I go in the browser and visit https://localhost:8443, and click through the warning messages, it does actually log stream and successfully make the request. But haven't been able to get node to make the request.

如果我进入浏览器并访问https:// localhost:8443,并单击警告消息,它实际上会记录流并成功发出请求。但是还没能得到节点来发出请求。

I would like to treat this as an HTTP1 server, so don't want to use the HTTP2 client to make the request. But tried using that and same thing.

我想将此视为HTTP1服务器,因此不要使用HTTP2客户端来发出请求。但尝试使用同样的东西。

1 个解决方案

#1


5  

HTTP/1 doesn't share the same request semantics as HTTP/2 so HTTP/1 clients need to be detected and handled in a HTTP/2 server. To support both you need to use the HTTP2 Compatibility API.

HTTP / 1不与HTTP / 2共享相同的请求语义,因此需要在HTTP / 2服务器中检测和处理HTTP / 1客户端。要同时支持,您需要使用HTTP2兼容性API。

The "hang" occurs when a HTTP1 client connects to a HTTP/2 server with allowHTTP1: true set but doesn't handle the HTTP/1 request.

当HTTP1客户端连接到具有allowHTTP1:true设置但未处理HTTP / 1请求的HTTP / 2服务器时,会发生“挂起”。

The examples are based on the Node documentation example code.

这些示例基于Node文档示例代码。

HTTP/1 and /2 Mixed Server

const http2 = require('http2')
const fs = require('fs')

var optiOns= {
  key: fs.readFileSync('server-key.pem'), 
  cert: fs.readFileSync('server-crt.pem'), 
  //ca: fs.readFileSync('ca-crt.pem'), 
  allowHTTP1: true,
}

var server = http2.createSecureServer(options, (req, res) => {
  // detects if it is a HTTPS request or HTTP/2
  const { socket: { alpnProtocol } } = (req.httpVersion === '2.0')
    ? req.stream.session 
    : req

  res.writeHead(200, { 'content-type': 'application/json' })
  res.end(JSON.stringify({
    alpnProtocol,
    httpVersion: req.httpVersion
  }))
})

server.listen(8443)

HTTP/2 Client

const http2 = require('http2')
const fs = require('fs')

const client = http2.connect('https://localhost:8443', {
    ca: fs.readFileSync('ca-crt.pem'),
    rejectUnauthorized: true,
})
client.on('socketError', (err) => console.error(err))
client.on('error', (err) => console.error(err))

const req = client.request({ ':path': '/' })

req.on('response', (headers, flags) => {
  for (const name in headers) {
    console.log('Header: "%s" "%s"', name, headers[name])
  }
})

req.setEncoding('utf8')
let data = ''
req.on('data', chunk => data += chunk)
req.on('end', () => {
  console.log('Data:', data)
  client.destroy()
})
req.end()

Then running:

→ node http2_client.js 
(node:34542) ExperimentalWarning: The http2 module is an experimental API.
Header: ":status" "200"
Header: "content-type" "application/json"
Header: "date" "Sat, 02 Dec 2017 23:27:21 GMT"
Data: {"alpnProtocol":"h2","httpVersion":"2.0"}

HTTP/1 Client

const https = require('https')
const fs = require('fs')

var optiOns= {
  method: 'GET',
  hostname: 'localhost',
  port: '8443',
  path: '/',
  protocol: 'https:',
  ca: fs.readFileSync('ca-crt.pem'),
  rejectUnauthorized: true,
  //agent: false
}

var req = https.request(options, function(res){
  var body = ''
  res.setEncoding('utf8')
  res.on('data', data => body += data)
  res.on('end', ()=> console.log('Body:', body))
})

req.on('response', respOnse=> {
  for (const name in response.headers) {
    console.log('Header: "%s" "%s"', name, response.headers[name])
  }
})

req.end()

Then running

→ node http1_client.js 
Header: "content-type" "application/json"
Header: "date" "Sat, 02 Dec 2017 23:27:08 GMT"
Header: "connection" "close"
Header: "transfer-encoding" "chunked"
Body: {"alpnProtocol":false,"httpVersion":"1.1"}

HTTP/2 Server

Using the plain HTTP/2 Server will work with the http2_client but will "hang" for a http1_client. The TLS connection from a HTTP/1 client will be closed when you remove allowHTTP1: true.

使用普通的HTTP / 2服务器将与http2_client一起使用,但对于http1_client将“挂起”。删除allowHTTP1:true时,将关闭来自HTTP / 1客户端的TLS连接。

const http2 = require('http2')
const fs = require('fs')

var optiOns= {
  key: fs.readFileSync('server-key.pem'), 
  cert: fs.readFileSync('server-crt.pem'), 
  ca: fs.readFileSync('ca-crt.pem'), 
  allowHTTP1: true,
}

var server = http2.createSecureServer(options)
server.on('error', error => console.log(error))
server.on('connect', cOnn=> console.log('connect', conn))
server.on('socketError', error => console.log('socketError', error))
server.on('frameError', error => console.log('frameError', error))
server.on('remoteSettings', settings => console.log('remote settings', settings))

server.on('stream', (stream, headers) => {
  console.log('stream', headers)
  stream.respond({
    'content-type': 'application/html',
    ':status': 200
  })
  console.log(stream.session)
  stream.end(JSON.stringify({
    alpnProtocol: stream.session.socket.alpnProtocol,
    httpVersion: "2"
  }))
})

server.listen(8443)

Certs

With the extended intermediate certificate setup detailed in the gist, the complete certificate chain for the CA needs to be supplied to the clients.

通过要点中详述的扩展中间证书设置,需要将完整的CA证书链提供给客户端。

cat ca/x/certs/x.public.pem > caxy.pem
cat ca/y/certs/y.public.pem >> caxy.pem

Then in the clients use this ca in the options.

然后在客户端中使用此选项中的ca.

{ 
  ca: fs.readFileSync('caxy.pem'),
}

These examples were run withe the following simple CA setup from this circle.com article:

这些示例是使用此circle.com文章中的以下简单CA设置运行的:

To simplify the configuration, let’s grab the following CA configuration file.

为了简化配置,让我们获取以下CA配置文件。

wget https://raw.githubusercontent.com/anders94/https-authorized-clients/master/keys/ca.cnf

Next, we’ll create a new certificate authority using this configuration.

接下来,我们将使用此配置创建新的证书颁发机构。

openssl req -new -x509 \
  -days 9999 \
  -config ca.cnf \
  -keyout ca-key.pem \
  -out ca-crt.pem

Now that we have our certificate authority in ca-key.pem and ca-crt.pem, let’s generate a private key for the server.

现在我们在ca-key.pem和ca-crt.pem中拥有了我们的证书颁发机构,让我们为服务器生成一个私钥。

openssl genrsa \
  -out server-key.pem \
  4096

Our next move is to generate a certificate signing request. Again to simplify configuration, let’s use server.cnf as a configuration shortcut.

我们的下一步是生成证书签名请求。再次简化配置,让我们使用server.cnf作为配置快捷方式。

wget https://raw.githubusercontent.com/anders94/https-authorized-clients/master/keys/server.cnf

Now we’ll generate the certificate signing request.

现在我们将生成证书签名请求。

openssl req -new \
  -config server.cnf \
  -key server-key.pem \
  -out server-csr.pem

Now let’s sign the request.

现在让我们签署请求。

openssl x509 -req -extfile server.cnf \
  -days 999 \
  -passin "pass:password" \
  -in server-csr.pem \
  -CA ca-crt.pem \
  -CAkey ca-key.pem \
  -CAcreateserial \
  -out server-crt.pem

推荐阅读
  • 本文讨论了在使用PHP cURL发送POST请求时,请求体在node.js中没有定义的问题。作者尝试了多种解决方案,但仍然无法解决该问题。同时提供了当前PHP代码示例。 ... [详细]
  • 怎么在PHP项目中实现一个HTTP断点续传功能发布时间:2021-01-1916:26:06来源:亿速云阅读:96作者:Le ... [详细]
  • 本文介绍了在mac环境下使用nginx配置nodejs代理服务器的步骤,包括安装nginx、创建目录和文件、配置代理的域名和日志记录等。 ... [详细]
  • IjustinheritedsomewebpageswhichusesMooTools.IneverusedMooTools.NowIneedtoaddsomef ... [详细]
  • mac php错误日志配置方法及错误级别修改
    本文介绍了在mac环境下配置php错误日志的方法,包括修改php.ini文件和httpd.conf文件的操作步骤。同时还介绍了如何修改错误级别,以及相应的错误级别参考链接。 ... [详细]
  • 基于Socket的多个客户端之间的聊天功能实现方法
    本文介绍了基于Socket的多个客户端之间实现聊天功能的方法,包括服务器端的实现和客户端的实现。服务器端通过每个用户的输出流向特定用户发送消息,而客户端通过输入流接收消息。同时,还介绍了相关的实体类和Socket的基本概念。 ... [详细]
  • 单页面应用 VS 多页面应用的区别和适用场景
    本文主要介绍了单页面应用(SPA)和多页面应用(MPA)的区别和适用场景。单页面应用只有一个主页面,所有内容都包含在主页面中,页面切换快但需要做相关的调优;多页面应用有多个独立的页面,每个页面都要加载相关资源,页面切换慢但适用于对SEO要求较高的应用。文章还提到了两者在资源加载、过渡动画、路由模式和数据传递方面的差异。 ... [详细]
  • java实现rstp格式转换使用ffmpeg实现linux命令第一步安装node.js和ffmpeg第二步搭建node.js启动websocket接收服务
    java实现rstp格式转换使用ffmpeg实现linux命令第一步安装node.js和ffmpeg第二步搭建node.js启动websocket接收服务第三步java实现 ... [详细]
  • 这篇“Webpack是怎么工作的”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大 ... [详细]
  • node.js中需要遍历数组并返回值的处理实在是搞不懂了... ... [详细]
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • 本文介绍了为什么要使用多进程处理TCP服务端,多进程的好处包括可靠性高和处理大量数据时速度快。然而,多进程不能共享进程空间,因此有一些变量不能共享。文章还提供了使用多进程实现TCP服务端的代码,并对代码进行了详细注释。 ... [详细]
  • 计算机存储系统的层次结构及其优势
    本文介绍了计算机存储系统的层次结构,包括高速缓存、主存储器和辅助存储器三个层次。通过分层存储数据可以提高程序的执行效率。计算机存储系统的层次结构将各种不同存储容量、存取速度和价格的存储器有机组合成整体,形成可寻址存储空间比主存储器空间大得多的存储整体。由于辅助存储器容量大、价格低,使得整体存储系统的平均价格降低。同时,高速缓存的存取速度可以和CPU的工作速度相匹配,进一步提高程序执行效率。 ... [详细]
  • 本文介绍了计算机网络的定义和通信流程,包括客户端编译文件、二进制转换、三层路由设备等。同时,还介绍了计算机网络中常用的关键词,如MAC地址和IP地址。 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
author-avatar
用户wuhqqnrd0m
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有