大佬教程收集整理的这篇文章主要介绍了如果node.js是单线程的,那么为什么server.listen()会返回?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
var http = require("http"); function main(){ // Console will print the message console.log('Server running at http://127.0.0.1:8080/'); var server = http.createServer(function (request,responsE) { // Send the http header // http Status: 200 : OK // Content Type: text/plain response.writeHead(200,{'Content-Type': 'text/plain'}); // Send the response body as "Hello World" response.end('Hello World\n'); }); server.listen(8080); //Why is this not blocking console.log('Main completed'); //main loop here prevents other stuff from working } main();
在像java或c这样的语言中我会期待两件事. server.listen都提供了一个事件循环,它会导致server.listen永远不会返回.或者server.listen生成一个新线程并在新线程中立即运行事件循环.然后它将@L_616_6@console.log,然后返回并关闭该程序.
为了测试这个,我还在console.log下面添加了一个繁忙的循环.
var http = require("http"); function main(){ // Console will print the message console.log('Server running at http://127.0.0.1:8080/'); var server = http.createServer(function (request,{'Content-Type': 'text/plain'}); // Send the response body as "Hello World" response.end('Hello World\n'); }); server.listen(8080); //Why is this not blocking console.log('Main completed'); while(true){ console.log('hi'); } } main();
Server.listen立即返回,然后按预期陷入繁忙循环.我的浏览器无法连接到服务器,这是预期的.
如果我删除busy循环并返回原始代码,一旦console.log(‘Main completed’);执行而不是程序退出,主线程跳回到事件循环.
这是如何运作的.为什么主线程返回后主线程会跳回到服务器代码中?
当您运行someElement.addEventListener(‘click’,handler)时,它会绑定一个事件侦听器,该事件侦听器将在someElement上触发click事件时将处理程序发送到回调队列.
http.createServer(handler)与server.listen(port)结合使用的方式非常相似. http.createServer(handler)返回一个eventEmitter,而server.listen(port)告诉node.js,当在给定端口上收到http请求时,应触发此事件.因此,当请求进入时,事件被触发,处理程序被推送到回调队列.
此时,事件循环callstack和回调队列如何交互只是一个简单的问题. callstack是当前正在执行的函数堆栈,回调队列是等待执行的回调集合,而事件循环是将回调队列的回调拉出并将它们发送到callstack.
因此,从某种意义上说,事件循环是保持一切运行的原因,但是,如果通过在其中一个回调中阻塞callstack使其无法循环,则事件循环永远不会再次运行并且回调永远不会被执行,从而导致破碎/反应迟钝的申请.
以上是大佬教程为你收集整理的如果node.js是单线程的,那么为什么server.listen()会返回?全部内容,希望文章能够帮你解决如果node.js是单线程的,那么为什么server.listen()会返回?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。