Node JS 채팅 소스
이번 포스팅에서는 Node JS를 활용한 채팅 소스 중 JSP 소스를 공유하려고 합니다.
먼저 소스 내용은 아래와 같습니다.
아래 소스를 보시고 궁금하신 내용이나 질문사항은 문의 주세요.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Node JS Socket.IO JavaScript</title> <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <script src="https://cdn.socket.io/socket.io-1.3.5.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io-stream/0.9.1/socket.io-stream.min.js"></script> <script type="text/javascript"> "use strict"; var session_id = '<%=session.getId()%>'; var session_ip = '<%=request.getRemoteAddr()%>'; $(document).ready(function(){
document.addEventListener('DOMContentLoaded', function () { if (!Notification) { alert('Desktop notifications not available in your browser. Try Chromium.'); return; } if (Notification.permission !== "granted") Notification.requestPermission(); }); var ChatMessage = function(type, data) { this.type = type; this.data = data; this.sessionId = session_id; this.ip = session_ip; } var Chat = {}; Chat.socket = null, Chat.initialize = function(url){ Chat.socket = io.connect(url); Chat.sendMessage(new ChatMessage('chat','Socket Connected!!'));
Chat.socket.on('answer', function(data){ console.log(data) Common.addMsg(data); }); Chat.socket.on('disconnect', function(){ console.log('Disconnect connection'); Chat.sendMessage(new ChatMessage('chat','Socket Disconnected!!')); }); }; Chat.sendMessage = function(chatMessage){ Chat.socket.emit('call', chatMessage); }; Chat.upload = function(file){
var uuid = Common.guid(); var stream = ss.createStream(); ss(Chat.socket).emit('upload', stream, { name: file.name, size: file.size, uuid: uuid });
var data = {}; data.type='tmp'; data.address = '127.0.0.1'; data.data = {}; data.data.name = file.name; data.data.size = file.size; data.data.uuid = uuid; Common.addMsg(data); var blobStream = ss.createBlobReadStream(file); var size = 0; blobStream.on('data', function(chunk){ size += chunk.length; $('.'+ uuid + ' .progress').text(Math.round( (size/file.size)*100) + '%'); if(size == file.size) { $('.'+uuid).remove(); Chat.sendMessage(new ChatMessage('file',{name:file.name, size:file.size, uuid:uuid})); } }); blobStream.pipe(stream); }; Chat.initialize('http://15.1.3.92:3303'); var box = $('#answer'); box.on('dragenter', Common.stopEvent); box.on('dragover', Common.stopEvent); box.on('drop', function (e) { e.originalEvent.preventDefault(); var files = e.originalEvent.dataTransfer.files; for (var i = 0; i < files.length; i++) { var file = files[i]; Chat.upload(file); } });
$('#content').keypress(function(e) { var content = this.value; var caret = Common.getCaret(this); if (e.keyCode == 13) { if(e.shiftKey){ this.value = content.substring(0, caret) + "\n" + content.substring(caret, content.length); $(this).scrollTop($(this)[0].scrollHeight); Common.stopEvent(e); } else { $('#send').click(); } return false; } }); $('#send').click(function(){ Chat.sendMessage(new ChatMessage('chat',$('#content').val())); $('#content').val(''); });
$(document).on('click', '.attachLink', function(){ var uuid = $(this).attr('uuid'); var originalFilename = $(this).text(); var deferred = $.Deferred(); var stream = ss.createStream(), fileBuffer = [], fileLength = 0; ss(Chat.socket).emit('download', stream, uuid, function (fileError, fileInfo) { console.log('fileInfo'+fileInfo) if (fileError) { console.log(fileError) deferred.reject(fileError); } else { console.log(['File Found!', fileInfo]); stream.on('data', function (chunk) { fileLength += chunk.length; var progress = Math.floor((fileLength / fileInfo.size) * 100); progress = Math.max(progress - 2, 1); deferred.notify(progress); fileBuffer.push(chunk); }); stream.on('end', function () { var filedata = new Uint8Array(fileLength), i = 0; fileBuffer.forEach(function (buff) { for (var j = 0; j < buff.length; j++) { filedata[i] = buff[j]; i++; } }); deferred.notify(100); Common.downloadFileFromBlob([filedata], originalFilename); deferred.resolve(); }); } }); return deferred; }); }); var Common = { byteConvertor : function(bytes) { bytes = parseInt( bytes ); var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB']; var e = Math.floor( Math.log( bytes ) / Math.log( 1024 ) ); if(e == "-Infinity") return "0 "+s[0]; else return ( bytes / Math.pow( 1024, Math.floor( e ) ) ).toFixed( 2 )+""+s[e]; }, stopEvent : function (e){ try{ event.stopPropagation(); }catch(e){} try{ e.preventDefault(); }catch(e){} }, getCaret : function (el) { if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { el.focus(); var r = document.selection.createRange(); if (r == null) return 0; var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; }, removeTag : function (str){ return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\n/g, "<br />").replace(/\t/g, " "); }, addMsg : function (data) { $('#answer').append(this.getTypeMsg(data)); $('#answer').scrollTop($('#answer')[0].scrollHeight); }, getFileName : function(str){ var len = str.length; var last = str.lastIndexOf('.'); if(last==-1) return str; return str.substring(0, last); }, getTypeMsg : function(data){ if(data.type == 'chat') { if(session_id != data.sessionId) Common.notify(data.address+'님 으로부터 메시지:', data.data); return '<p><span class="who">'+data.address+'</span><span class="message">' + Common.removeTag(data.data) + '</span><span class="ctime">'+data.ctime.substring(10)+'</span></p>'; } else if(data.type == 'file') { if(session_id != data.sessionId) Common.notify(data.address+'님 으로부터 파일전송:', data.data.name); return '<p><span class="who">'+data.address+'</span><span class="message"><a uuid="'+data.data.uuid+'" href="#" class="attachLink">' + Common.removeTag(data.data.name) + '</a> '+Common.byteConvertor(data.data.size)+' <span class="'+data.data.name+'"></span></span><span class="ctime">'+data.ctime.substring(10)+'</span></p>'; } else if(data.type == 'tmp') { return '<p class="'+data.data.uuid+'"><span class="who">'+data.address+'</span><span class="message"><a href="#">' + Common.removeTag(data.data.name) + '</a> '+Common.byteConvertor(data.data.size)+' <span class="progress"></span></span><span class="ctime">now</span></p>'; } }, guid : function() { function s4() { return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); }, downloadFileFromBlob : function(data, fileName){ var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none";
var blob = new Blob(data, { type : "octet/stream" }), url = window.URL.createObjectURL(blob); a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); }, notify : function(title, body) { if (Notification.permission !== "granted") Notification.requestPermission(); else { var notification = new Notification(title, { icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png', body: body, }); setTimeout(function(){ notification.close(); }, 2000); notification.onclick = function () { window.focus(); }; } } }; </script> <style type="text/css"> html,body { height: 100%; overflow: hidden; margin: 0px; padding: 0px; } #answer { border: 1px solid #ccc; height: -webkit-calc(100% - (50px)); height: calc(100% - (50px)); font-family : 굴림,돋움,나눔고딕,Verdana; font-size: 12px; padding: 0px; margin: 0px; overflow: auto; background-image: url("aa.jpg"); /* background-repeat: no-repeat; */ } .message { background-color: white; display: inline-block; padding: 5px; max-width: calc(100% - 200px); word-break:break-all;
} .ctime { vertical-align: sub; color: #DFDFDF; padding-left: 5px; font-size: 11px; } .who { color: #DFDFDF; vertical-align: top; padding-left: 5px; padding-right: 5px; display: inline-block; width: 70px; text-align: right; } #content { line-height: 13px; overflow: auto; border: 1px solid #ccc; width: calc(100% - 73px); height: 41px; } #send { border: 1px solid #ccc; height: 47px; vertical-align: top; width: 60px; } .inputArea { } </style> </head> <body> <div id="answer"></div> <div class="inputArea"> <textarea id="content"></textarea> <input type="button" id="send" value="Send"></input> </div> <div style="display: none;"> <input type="file" id="file" /> <div id="stat">Ready...</div> </div> </body> </html> |
'JAVASCRIPT > Node.js' 카테고리의 다른 글
Node JS 채팅 (0) | 2017.10.25 |
---|