에 컬을 통해 실행할 때 다음과 같은 간단한 NodeJS 코드가 있습니다 :NodeJS 코드는 다르게 실행 터미널
var http = require("http");
http.createServer(function(request, response){
response.writeHead(200);
setTimeout(function(){
response.write("This printed 3 secs later, ait?");
response.end();
}, 3000);
response.write("This will be printed before.\n");
}).listen(8080);
나는 node scriptname.js
으로 스크립트를 실행 한 다음과 같이 터미널에 컬을 통해 액세스하는 경우 :
curl http://localhost:8080
내가 먼저 그것이 This printed 3 secs later, ait?
인쇄 삼초 후 다음 This will be printed before.
을 인쇄, 예상대로 출력을 얻을.
그러나 내 브라우저 (Chrome, Firefox의 최신 버전) 페이지에서 http://localhost:8080
을 열면 3 초 동안로드되고 This will be printed before. This printed 3 secs later, ait?
텍스트가 한꺼번에 인쇄됩니다. 왜 이런 일이 일어나고 브라우저에서 어떻게 동일한 동작을 수행 할 수 있습니까?
편집 : 켄은 그의 대답
하고 가서 Socket.IO을 확인하는 것이 좋습니다, 나는 express 및 Socket.IO를 사용하여이 작업을 예를 내놓았다 :에 명시된 바와 같이 그래서 ...이 때문에 내용을 렌더링하는 렌더링 엔진을 브라우저의 동작을하는 것입니다. 렌더링 엔진은 response.end();
//timeoutTest.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(8080);
app.use(express.static(__dirname + '/'));
app.get('/', function (req, res) {
res.sendfile(__dirname + '/timeoutTest.html');
});
io.sockets.on('connection', function (client) {
client.emit('msg', "This prints right now on connection.");
setTimeout(function(){
client.emit('msg', "This prints out after 3 secs.");
}, 3000);
});
// timeoutTest. html
<!DOCTYPE html>
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
var server = io.connect('http://localhost');
server.on('msg', function(data){
$('body').append(data + "<br/>");
});
});
</script>
</head>
<body>
</body>
</html>
추 신. 서버 - 브라우저 상호 작용 문제의 초보자를 위해'Socket.IO'를 추천했습니다. 이 기술은 일반적으로'RPC (remote procedure cal)'라고합니다. 'Socket.IO'는 많은 사람들에게 친숙하며 웹에서 풍부한 자원을 찾을 수 있기 때문에 시작하는 것이 좋습니다. 나중에 참조 할 경우 노드와 브라우저간에 RPC를 수행하는 방대한 라이브러리이므로 개인적으로 더 이상 사용하지 않습니다. RPC를보다 간결하고 정교하게 (내가 생각하기에) "RPCify"와 함께 https://github.com/substack/dnode 또는 https://github.com/dominictarr/rpc-stream을 사용하면됩니다. –
관련 질문에 대한 답변은 여기를 참조하십시오. http://stackoverflow.com/questions/12832402/is-socket-io-a-must-in-developing-client-apps-for-nodejs-servers –
추가 의견을 보내 주셔서 감사합니다! – Nikola