기본 콘텐츠로 건너뛰기

node.js 채팅 서버와 클라이언트 구현(~ing)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
var http = require('http'); // module 추출
var fs = require('fs');
var socketio = require('socket.io');
var mysql = require('mysql');
 
var client = mysql.createConnection({
    user: 'root',
    password: '********'// 실제로는 비밀번호를 입력을 해야 접속을 합니다....
    database: 'company'
});
 
var server = http.createServer(function (request, response) {
    fs.readFile('chat.html'function (error, data) {
        response.writeHead(200, { 'Content-Type''text/html' });
        response.end(data);
    });
}).listen(80function () {
    console.log('Server Running.......');
});
 
var io = socketio.listen(server);
 
io.sockets.on('connection'function (socket) {
    console.log('connection');
    socket.on('message'function (data) {
        console.log('name:' +data.name );
        console.log('message : ' +data.message);
        console.log('date' + data.date + '\n');
        console.log('\n');
        
        client.query('insert into message(name, messages,date) values(?,?,?)', [data.name, data.message, data.date], function () {
        });
        io.sockets.emit('message', data);
    });
});
 
cs
서버측 코드이다.

우선 클라이언트 측에서 데이터를 보내게 되면 25번째 

1
2
3
4
5
6
7
8
9
10
11
socket.on('message'function (data) {
        console.log('name:' +data.name );
        console.log('message : ' +data.message);
        console.log('date' + data.date + '\n');
        console.log('\n');
        
        client.query('insert into message(name, messages,date) values(?,?,?)', [data.name, data.message, data.date], function () {
        });
        io.sockets.emit('message', data);
    });
 
cs
cs
위 코드가 실행을 하게 된다

데이터가 정상적으로 잘 넘어가는지 확인을 하기 위해 console.log로 서버측에서 데이터를 확인을 하고

client.query를 이용하여 데이터를 message라는 테이블에다가 넣었다.

 

그리고 다시 데이터를 클라이언트 측으로 뿌려준다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<!DOCTYPE html>
<html>
<head>
    <title>Mobile chat</title>
    <meta name="viewport" content="width = device-width, initial-scale=1" />
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
    
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>    
    <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    
    <script>
    $(document).ready(function(){
        var socket = io.connect();
        
        socket.on('message',function(data){
            
            var output = '';
           
            output += '
  • '
  • ;
                output += '     

    '

     + data.name + '
    ';
                output += '     ' + data.message + '
    ';
                output += '     ' + data.date + '
    ';
                output += '
    ';
        
                $(output).prependTo('#content');
                //$('#content').listview('refresh');
            
            });
            
            $('button').click(function () {
                if($('#name').val()!=''){
                    socket.emit('message',{
                        name :$('#name').val(),
                        message:$('#message').val(),
                        date: new Date().toUTCString()
                    
                    });
                }
            });
        
        });
                
     </script>
    </head>
    <body>
     
        <div data-role="page">
            <div data-role="header">
                <h1>socket.io chat</h1>
            </div>
            <div data-role="content">
                <h3>Nick name</h3>
                <input id="name" />
                <a data-role="button" href="#chatpage">start chat</a>
            </div>
        </div>
     
        <div data-role="page" id="chatpage">
            <div data-role="header">
                <h1>socket.io</h1>
            </div>
            
            <h1></h1>
            
            <div data-role="content">
                <input id="message" />
                <button>message send</button>
                <ul id="content" data-role="listview" data-inset="true"></ul>
            </div>
        </div>
     
    </body>
    </html>
     
    cs cs
    cs 
    클라이언트 측 소스

    클라이언트는 우선 클릭 이벤트가 발생할때 닉네임이 없으면 데이터가 전송이 되지 않도록 하였다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    socket.on('message',function(data){
                
                var output = '';
               
                output += '
  • '
  • ;
                output += '     

    '

     + data.name + '
    ';
                output += '     ' + data.message + '
    ';
                output += '     ' + data.date + '
    ';
                output += '
    ';
        
                $(output).prependTo('#content');
                //$('#content').listview('refresh');
            
            });
     


    s
    이부분은 서버에서 클라이언트 측으로 데이터를 보낸후 
    클라이언트가 서버에서 받은 데이터를 다시 재 조립을 하여 문서에 붙이는 부분이다.


    약간의 수정을 해보자

    기존의 클라이언트 소스에서
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    <script>
        $(document).ready(function(){
            var socket = io.connect();
            
            socket.on('message',function(data){
                
                var output = '';
               
                output += '
  • '
  • ;
                output += '     

     '

     + data.name + '
    ';
                output += '      ' + data.message + '
    ';
                output += '      ' + data.date + '
    ';
                output += '
    ';
        
                $(output).prependTo('#content');
                $('#content').listview('refresh');
            
            });
            
            $('button').click(function () {
                if($('#name').val()!=''){
                    socket.emit('message',{
                        name :$('#name').val(),
                        message:$('#message').val(),
                        date: new Date().toUTCString()
                    
                    });
                }
            });
        
        });
        </script>
     
    cs
     
    닉네임을 치고 내용을 입력을 하는데

    닉네임이 없을때만 전송이 안되었던 부분을

    다음과 같이 수정을 하였다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    <script>
        $(document).ready(function(){
            var socket = io.connect();
            
            socket.on('message',function(data){
                
                var output = '';
               
                output += '
  • '
  • ;
                output += '     

    nick : '

     + data.name + '
    ';
                output += '     message : ' + data.message + '
    ';
                output += '     date : ' + data.date + '
    ';
                output += '
    ';
        
                $(output).prependTo('#content');
                $('#content').listview('refresh');
            
            });
            
            $('button').click(function () {
                if($('#name').val()!='' && $('#message').val()!=''){
                    socket.emit('message',{
                        name :$('#name').val(),
                        message:$('#message').val(),
                        date: new Date().toUTCString()
                    
                    });
                }
            });
        
        });
        </script>
     
    cs
    조건을 내용도 아무것도 없을때는 클릭 이벤트가 발생을하여도 실행이 되지 않게 바꿨다.

     
    출력을 좀더 보기 쉽게 나타내었다.

    댓글

    이 블로그의 인기 게시물

    [node.js] 파일 리더기 만들기 - 사용 모듈 정리, pdf 구조, hwp 구조

    pdf -> html 변환 가장 무난하다. 기본적으로 pdf는 htm와 비슷한 형태의 구조를 가지고 있다. 크게 header , body , xref table , trailer 의 구조로 되어있다. pdf는 환경에 상관없이 표현을 하기 위한 목적을 가지고 있는 파일이다. 이런 이유 때문에 무난히 진행이 된 것 같다. pdf2htmlex와 pdftohtmljs라는 모듈을 이용을 했다. var pdftohtml = require ( 'pdftohtmljs' ) ; var converter = new pdftohtml ( 'test.pdf' , "sample.html" ) ; converter . convert ( 'ipad' ) . then ( function ( ) { console . log ( "Success" ) ; } ) . catch ( function ( err ) { console . error ( "Conversion error: " + err ) ; } ) ; 이미지나, text같은 것들이 거의 100%로 변환이 된다. docx -> html 변환 docx파일을 html파일로 변환을 할 때는 style 적용과 한글이 깨지는 문제가 있다. 텍스트들을 전부 잘 읽기는 하는데 스타일 정보를 제대로 가져오지 못하기 때문에 좀 애매하다 - Headings. - Lists. - Customisable mapping from your own docx styles to HTML. For instance, you could convert WarningHeading to h1.warning by providing an appropriate style ...

    [css] css로 프린트 방지하기

    웹에서 프린트 제어가 불가능 한 줄 알았는데 프린트 클릭 시  스크립트로 해당 이벤트를 받아올 수 있다. 하지만 스크립트를 사용하는 방법은 브라우저마다 작동을 하지 않을 수 있다. 좀 더 찾아보니 css로 인쇄되는 영역을 제어를 해줄 수 있다.  @media print 를 이용하면 된다. < html > < head > < title > print test page < / title > < style > @media print { . np { display : none ; } } < / style > < / head > < body > < div class = "np" > test < / div > < div > test1 < / div > < div > test1 < / div > < div > test1 < / div > < / body > < / html > 위 코드를 보면 np 클래스를 @media print에 넣어주었다. @media print는 인쇄됐을 때의 스타일을 지정을 해주는 것이다.  위에서는 해당 페이지를 인쇄할 때 p를 display : none으로 가려주었다. @media print를 이용하면 좀 더 멋진 인쇄물을 만들 수 ...

    [알고리즘] snake게임 알고리즘

    막무가네로 알고리즘을 공부하면 재미가 없으니 게임을 접목하여 다루어 보도록 하겠습니다. 게임의 대상은 스네이크 게임입니다. 많은 사람들은 어릴 때 뱀게임을 많이 해봤을 것 입니다. 이번에 다뤄볼 주제는 뱀이 움직임을 어떻게 구현을 할지 알아보겠습니다. 뱀은 크게 3가지의 경우가 있습니다 1. 가장 중요한 뱀을 움직이기 2. 음식먹기 이때 뱀은 크기가 늘어나야 합니다. 3. 뱀이 움직이는 정책   - 뱀이 움직이지 못하는 경우는 : 우측방향에서 좌측 방향으로 OR 위에 아래 방향고 같이 180도 반전되는 움직임은 막겠습니다. 순수한 알고리즘을 만드는 과정이기 때문에 음식을 먹었는지 안먹었는지 판단하는 부분은 랜덤으로 판단을 하도록 하겠습니다. def is_eat(): return random.choice([1, 0]) 랜덤으로 1, 0을 반환을 해줍니다. 실제로 게임을 만든다면 해당 함수는 뱀의 머리가 음식의 좌표와 같은지 검사를 해주면 되겠습니다. key_position_map = { 'w': [-1, 0], # up 's': [1, 0], # down 'a': [0, -1], # left 'd': [0, 1] # right } direction = key_position_map.get('d') 다음으로는 키맵핑을 한 오브젝트 입니다. direction은 현재 뱀의 방향을 나타냅니다. snake_body = [[2, 3], [1, 3],[1, 2], [1, 1]] 주인공이 되는 뱀의 좌표들 입니다. while True: key = input() new_direction = key_position_map.get(key) if new_direction and direction_check(direction, new_direction): directi...