1
하나의 nodejs 스크립트에서 일반적인 웹 서버 페이지와 websocket 서비스를 만들 수 있습니까?NodeJs의 한 스크립트에서 두 개의 서버를 만들 수 있습니까?
하나의 nodejs 스크립트에서 일반적인 웹 서버 페이지와 websocket 서비스를 만들 수 있습니까?NodeJs의 한 스크립트에서 두 개의 서버를 만들 수 있습니까?
예, 실제로 이것은 거의 발생합니다. 단일 TCP 수신기는 웹 요청뿐만 아니라 HTTP 요청도 처리하지만 HTTP 요청으로 시작하지만 프로토콜을 원시 TCP 웹 소켓으로 변경합니다. socket.io의 모든 예제는 이것을 설명합니다.
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});