$ yum install gcc gcc-c++ $ yum install openssl-devel make $ wget http://nodejs.org/dist/v0.10.31/node-v0.10.31.tar.gz ※ http://nodejs.org/download/ 최신버젼받기 $ tar xvfz node-v0.10.31.tar.gz $ cd node-v0.10.31 $ ./configure --prefix=/data/nodejs { 'target_defaults': { 'cflags': [], 'default_configuration': 'Release', 'defines': [], 'include_dirs': [], 'libraries': []}, 'variables': { 'clang': 0, 'gcc_version': 44, 'host_arch': 'x64', 'node_install_npm': 'true', 'node_prefix': '/data/nodejs', 'node_shared_cares': 'false', 'node_shared_http_parser': 'false', 'node_shared_libuv': 'false', 'node_shared_openssl': 'false', 'node_shared_v8': 'false', 'node_shared_zlib': 'false', 'node_tag': '', 'node_unsafe_optimizations': 0, 'node_use_dtrace': 'false', 'node_use_etw': 'false', 'node_use_openssl': 'true', 'node_use_perfctr': 'false', 'node_use_systemtap': 'false', 'python': '/usr/bin/python', 'target_arch': 'x64', 'v8_enable_gdbjit': 0, 'v8_no_strict_aliasing': 1, 'v8_use_snapshot': 'true', 'want_separate_host_toolset': 0}} creating ./config.gypi creating ./config.mk $ make && make install ##### bin Path는 계정 및 shell환경에 맞게 profile 에 등록하기## $ vi /root/.bash_profile PATH=$PATH:$HOME/bin PATH=$PATH:/data/nodejs/bin ##nodjs bin등록 export PATH source /root/.bash_profile ############################################################## $ /data/nodejs/bin/node -v v0.10.31 ## npm 이용한 forever 데몬프로그램 설치######################## $ /data/nodejs/bin/npm install -g forever ## npm 이용한 socket.io 설치################################### $ /data/nodejs/bin/npm install -g socket.io
Programming/node.js2014. 9. 15. 18:21
Programming/node.js2014. 9. 15. 15:49
Node.js 책 잠시 보고 만든 샘플입니다.
그냥 참고용으로!!ㅎㅎ
1. Server Side Node.js Socket.io
- var io = require('socket.io').listen(80);
- var clients = {};
- io.sockets.on('connection', function (socket){
- //입장 및 닉네임체크
- socket.on('create_nickname',function(nickname,returnFunction){
- //닉네임중복체크
- var returnCode = 1;
- for ( var i in clients ){
- if ( clients[i] == nickname ){
- returnCode = -1;
- break;
- }
- }
- //닉네임체크확인 결과 전달
- returnFunction(returnCode);
- //닉네임체크 유효화됨
- if ( returnCode == 1 ) {
- //클라이언트 닉네임등록
- clients[socket.id] = nickname;
- //새접속자로인한 전체 유저리스트 전달함
- io.sockets.emit('user_list',clients);
- //전체유저 메세지전송
- io.sockets.emit('msgPush',{"nickname":"시스템","msg":clients[socket.id]+" 유저가 입장하셨습니다."});
- console.log('CONNECT : ',nickname+' ['+socket.id+'] '+'('+Object.keys(clients).length+'명)');
- }
- });
- socket.on('msgSend',function(data){
- //자신을 제외한 전체유저에게 메세지전송
- socket.broadcast.emit('msgPush',data);
- /*
- *socket.emit('msgPush',data);//자신에게만 보낼때
- *socket.broadcast.emit('msgPush',data);//자신제외 전체유저
- *io.sockets.emit('msgPush',data);//자신포함 전체유저에게
- *io.sockets.in(socket_id).emit('msgPush',data);//특정유저에게 귓속말시 socket_id추가입력하면됨
- *io.of('namespace').emit('msgPush', data); //of 지정된 name space의 유저
- */
- console.log('Chat Msg : ','['+data['nickname']+'] '+data['msg']);
- });
- //접속종료시처리
- socket.on('disconnect', function(){
- if ( clients[socket.id] ){
- //유저이탈 메세지전달
- io.sockets.emit('msgPush',{"nickname":"시스템","msg":clients[socket.id]+" 유저가 나가셨습니다."});
- console.log('DISCONNECT : ', clients[socket.id]);
- //이탈유저닉네임삭제
- delete clients[socket.id];
- //유저이탈 전체유저리스트 갱신
- io.sockets.emit('user_list',clients);
- }else{
- console.log('NOT USER DISCONNECT : ', socket.id);
- }
- });
- });
2. Client
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Chat</title>
- </head>
- <body>
- <div id="chatJoin">
- <form id="chatJoinForm">
- 대화명 : <input id="nickname" name="nickname" type="text"> <input type="submit" value="입장">
- </form>
- </div>
- <div id="chatRoom" style="display:none;">
- <div id="msgList" style="float:left;width:500px;height:300px;border:1px solid #1D365D;overflow:auto;"></div>
- <div style="float:left;width:100px;height:300px;border:1px solid #1D365D;margin-left:3px;">
- <div style="border-bottom:1px solid #1D365D;">접속자</div>
- <div id="userList"></div>
- </div>
- <div style="clear:both;">
- <form id="chatMsgForm">ChatMsg : <input id="msgText" name="msg" type="text"> <input type="submit" value="전송"></form>
- </div>
- </div>
- </body>
- <script type="text/javascript" src="jquery-1.11.1.min.js"></script>
- <script type="text/javascript" src="socket.io.js"></script>
- <script type="text/javascript">
- $(function(){
- var socket;
- function createNickname(nickName){
- socket.emit('create_nickname',nickName,function(returnCode){
- if ( returnCode == 1 ){
- //정상적인 닉네임
- $('#chatJoin').hide();
- $('#chatRoom').show();
- $('#msgText').focus();
- }else{ //아니면 닉네임중복됨
- alert('존재하는 닉네임입니다.');
- $('#nickname').focus();
- socket.disconnect();
- }
- });
- }
- function msgAdd(data){
- var sHtml = '<div><span style="color:blue;">'+data['nickname']+'</span> : '+data['msg']+'</div>';
- $('#msgList').append(sHtml);
- $("#msgList").scrollTop($("#msgList")[0].scrollHeight);
- }
- $('#chatMsgForm').submit(function(event){
- event.preventDefault();
- var data = {"nickname":$('#nickname').val(),"msg":$('#msgText').val()}
- msgAdd(data);
- $('#msgText').val('');
- $('#msgText').focus();
- //서버에 입력메세지전달
- socket.emit('msgSend', data);
- });
- $('#chatJoinForm').submit(function(event){
- event.preventDefault();
- if ( !$('#nickname').val() ){
- alert("닉네임을 입력해주세요");
- $('#nickname').focus();
- return false;
- }
- /*
- *https://github.com/automattic/socket.io-client
- */
- socket = io.connect('http://127.0.0.1', {'forceNew':true,reconnection:false});
- socket.on('connect', function () {
- createNickname($('#nickname').val());
- });
- socket.on('user_list',function(clients){
- //심플테스트 버젼이라서 삭제하고 새로 갱신하는방안
- $('#userList').html('');
- for ( var i in clients ){
- if ( clients[i] == $('#nickname').val() ){
- sHtml = '<div style="font-weight:bold;">'+clients[i]+'</div>';
- }else{
- sHtml = '<div>'+clients[i]+'</div>';
- }
- $('#userList').append(sHtml);
- }
- });
- socket.on('msgPush',function(data){
- msgAdd(data);
- });
- socket.on('disconnect', function(){
- $('#msgList').html('');
- $('#nickname').val('');
- $('#chatJoin').show();
- $('#chatRoom').hide();
- alert('Server Disconnect');
- });
- socket.on('connect_error', function (data) {
- alert('CONNECT_ERROR : '+data);
- });
- });
- });
- </script>
- </html>
Programming/node.js2014. 9. 13. 11:44
메뉴얼 사이트
- Application : http://expressjs.com/api.html#express
- Request : http://expressjs.com/api.html#req.params
- Response : http://expressjs.com/api.html#res.status
- Router : http://expressjs.com/api.html#router
- Middleware : http://expressjs.com/api.html#middleware.api
테스트 샘플자료 (자세한 내용은 위에 API 참조하면 방대함 정규식처리등 많음)
- var express = require('express'), http = require('http');
- var bodyParser = require('body-parser');
- var app = express();
- app.use(bodyParser());
- app.all('*', function( req, res, next){
- res.writeHead(200,{
- "Content-Type" : "text/plain"
- });
- next();
- });
- app.get("/", function( req, res){
- res.end("HOME DIR : /");
- });
- app.get("/test", function( req, res){
- res.end("HOME DIR : /test");
- });
- app.get("/params/:user", function( req, res){
- var sText = " Params : "+req.params.user; // OR req.param('user')
- sText += "\n GET : "+req.query.q; //search?q=test OR req.param('q')
- sText += "\n POST : "+req.param('name'); //POST name=tobi
- //sText += "Cookie : "+req.cookies.name; // Cookie: name=tj
- sText += "\n ip : "+req.ip; // req.ips When "trust proxy" is `true`, parse the "X-Forwarded-For"
- res.end(sText);
- });
- app.get("*", function( req, res){
- res.end("NOT PAGE");
- });
- http.createServer(app).listen(80, '127.0.0.1');
- console.log('HTTP URL : http://127.0.0.1:80/');