개발모음집

Passing chat data from socket.io client to socket.io server 본문

Server/node.js

Passing chat data from socket.io client to socket.io server

void 2019. 12. 18. 10:00

Client 

라이브러리 : socket-io-client (https://github.com/socketio/socket.io-client)

 

package.json

{
  "name": "socketio-client",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "start": "node app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "socket.io-client": "^2.3.0"
  }
}

 

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>채팅</title>
    <link rel="stylesheet" href="./index.css">
    <!--http://localhost:8080 는 서버의 주소를 말한다. 서버에 있는 파일을 가져오는 것-->
    <script src="http://localhost:8080/socket.io/socket.io.js"></script>
    <script src="index.js"></script>
</head>
<body>
<div id="main">
    <div id="chat">
        <!-- 채팅 메시지 영역 -->
    </div>
    <div>
        <input type="text" id="test" placeholder="메시지를 입력해주세요..">
        <button onclick="send()">전송</button>
    </div>
</div>
</body>
</html>

app.js

let express = require('express');
let app = express();
let indexDir = `/public`;

app.use(express.static(__dirname+ indexDir));

app.listen(8843, function() {
    console.log(`Server running`);
});

 

index.js

var socket = io('http://localhost:8080');
/* 접속 되었을 때 실행 */
socket.on('connect', function() {
    console.log('connect');
    /* 이름을 입력받고 */
    var name = prompt('반갑습니다!', '')

    /* 이름이 빈칸인 경우 */
    if(!name) {
        name = '익명'
    }

    /* 서버에 새로운 유저가 왔다고 알림 */
    socket.emit('newUser', name)
})

/* 메시지 전송 함수 */
function send() {
    // 입력되어있는 데이터 가져오기
    var message = document.getElementById('test').value;


    console.log(message);

    // 가져왔으니 데이터 빈칸으로 변경
    document.getElementById('test').value = ''

    // 내가 전송할 메시지 클라이언트에게 표시
    var chat = document.getElementById('chat')
    var msg = document.createElement('div')
    var node = document.createTextNode(message)
    msg.classList.add('me')
    msg.appendChild(node)
    chat.appendChild(msg)

    // 서버로 message 이벤트 전달 + 데이터와 함께
    socket.emit('message', {type: 'message', message: message})
}

 

 

Server

라이브러리 (https://socket.io/)

package.json

{
  "name": "socketio-server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "socket.io": "^2.3.0",
  }
}

 

app.js

const express = require('express');
const socket = require('socket.io');
const http = require('http');
const fs = require('fs');
const app = express();
// express http 서버 생성
const server = http.createServer(app);
//생성된 서버를 socket.io에 바인딩
const io = socket(server);

io.sockets.on('connect', function(socket) {
    console.log('adfsdfasfsdfsad');
    /* 새로운 유저가 접속했을 경우 다른 소켓에게도 알려줌 */
    socket.on('newUser', function(name) {
        console.log(name + ' 님이 접속하였습니다.');

        /* 소켓에 이름 저장해두기 */
        socket.name = name;

        /* 모든 소켓에게 전송 */
        io.sockets.emit('update', {type: 'connect', name: 'SERVER', message: name + '님이 접속하였습니다.'})
    });

    /* 전송한 메시지 받기 */
    socket.on('message', function(data) {
        /* 받은 데이터에 누가 보냈는지 이름을 추가 */
        data.name = socket.name;

        console.log(data);

        /* 보낸 사람을 제외한 나머지 유저에게 메시지 전송 */
        socket.broadcast.emit('update', data);
    });
    
});

/* 서버를 8080 포트로 listen */
server.listen(8080, function() {
    console.log('서버 실행 중..')
});

 

 

서버코드 출처 : https://codevkr.tistory.com/62?category=719250