가. 언어유형/Node.js
Node.js Server 실행 시키기
LemonDory
2015. 3. 31. 11:16
아꿈사 스터디 블로그에서 꽃집총각님이 작성하신 글을 보고 직접 구현해 보았습니다.
원본 주소 :
http://cafe.naver.com/architect1/2454var app = require('http').createServer(handler) , fs = require('fs') , exec = require( 'child_process' ) app.listen(8080); 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.on( 'myMsg', function( data ) { for( name in data ) { console.log( data[name] ); } console.log( data ); var ack = packetHandler[ data.id ]( data.data ); ack.id = data.id; socket.emit( 'myMsg', ack ); }); }); var packetHandler = { 'turn on' : function( data ) { exec.exec( 'remoConsole.exe on' ); return { msg : 'TV is turned on.' }; }, 'turn off' : function( data ) { exec.exec( 'remoConsole.exe off' ); return { msg : 'TV is turned off.' }; }, 'channel' : function( data ) { exec.exec( 'remoConsole.exe channel ' + data ); return { msg : 'change channel to ' + data }; }, } |
Nodejs 공식 홈페이지(
http://nodejs.org)에서
윈도우용 설치 파일을 다운로드 받아 설치한다.
그리고 cmd 명령창에서 다음 명령을 실행하여 socket.io를 설치한다.
새로운 폴더(d:\remoteWeb)를 생성하고 다음과 같이 파일을 작성한다.
index.html
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://192.168.0.4/');
function execute(command)
{
socket.emit('execute', {cmd: command});
}
</script>
</head>
<body>
<button type="button" style="width:300px;height:150px;font-size:40pt;" onclick="execute('calc on')">Calc on</button>
<button type="button" style="width:300px;height:150px;font-size:40pt;" onclick="execute('calc off')">Calc Off</button>
</body>
</html>
|
cmd 명령창에서 다음과 같이 입력한다.
cd /d "d:\remoteWeb"
node server.js
이제 서버가 정상적으로 실행 되었으므로, 웹페이지에서 확인을 하면 된다.
http://192.168.0.4 로 접속한다.
(자신의 환경에 맞는 IP로 index.html을 수정하고 사용하시면 됩니다.)