[명우니닷컴] 웹 실시간 그림판 만들기(4)

류명운

·

2016. 3. 2. 01:27

반응형

작업 내역    : node.js 웹 소켓 모듈 서버를 이용한 실시간 그림판 구현



진행 중 작업 : 데스크탑 및 모바일 최적화 완료



앞으로 진행해야할 사항

 1) 데이터베이스 연동 (사용자가 캔버스 내에 작업한 내역이 유지되도록 - 최대 5만건 제한) - DB 서버로 사용할 고정 IP 필요

 2) 그림 도구 추가 (펜 & 지우개 굵기 선택, 모든 색 지원을 위한 팔레트 라이브러리 추가)

 3) 실시간 유저 목록 - 입장 시 닉네임을 받아 리스트 형식으로 유지하거나 / 마우스 오버 좌표 값에 따른 유저 닉네임 노출

 4) 각 유저마다 다른 브라우저 프레임 크기에 대한 동기화 - 열심히 검색해볼것.....



테스트 주소 :

 http://myeonguni.com



진행 결과물



관련 소스코드


1. nodeWS.js [Server]

var WebSocketServer = require('websocket').server;
var http = require('http');
var clients = [];
var idList = [];
var id = 0;
 var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);//콘솔출력
    response.writeHead(404);
    response.end();
});
server.listen(8000, function() { //아파치톰캣과 포트번호가 겹치기때문에 8000으로 설정
    console.log((new Date()) + ' 서버가 구동되었니다 - 포트넘버:8000'); 
});
 
wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});
 
function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}
 
 
wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }
 
    var connection = request.accept(null, request.origin);
 
    clients.push(connection);
    // 임의로 id값을 할당함. request.key값으로 client 구분
    id++;
 	console.log(id);
    console.log('[연결]'+(new Date()) + ' 새로운 접속자가 들어왔습니다. ('+connection.remoteAddress +')');


    connection.on('message', function(message) {
        if (message.type === 'utf8') {
			var temp;
			temp = message.utf8Data.split(',');
			if(temp[0]=='nick'){ //접속 유저 리스트
				idList[id-1] = temp[1];
				msg = "nick,";
				for(var i in idList){
					msg += temp[i];
				}
				clients.forEach(function(cli) {
					cli.sendUTF(msg);
				});
			}else{
	            console.log('Received Message: ' + message.utf8Data);
	            clients.forEach(function(cli) {
	                msg = message.utf8Data;
					cli.sendUTF(msg);
	            });
			}
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
        }
    });
    connection.on('close', function(reasonCode, description) {
		id--;
        console.log('[연결해제]'+(new Date()) + connection.remoteAddress + ' 님께서 연결이 해제되었습니다.');
    });
});



2. main.html [Client]


	
    
	


	
    
    
	



이 브라우저에서는 HTML5 CANVAS를 지원하지 않습니다.


반응형