donaricano-btn

1. 다른유저가 접속했는지 확인

앞의 소스들은 다른 소켓(클라이언트)이 접속을 했는지 않했는지 확인을 할 수 없었습니다. 
이번 장에서는 socket.broadcast를 이용하여 접속 여부를 기능을 추가해보도록 하겠습니다.

2. 서버 소켓

index.js

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);

app.get('/', function(req, res){
	res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
	socket.broadcast.emit('chat message', 'user connection...');
	socket.on('chat message', function(msg){
		io.emit('chat message', msg);
	});
	socket.on('disconnect', function(){
		socket.broadcast.emit('chat message', 'user disconnection...');
	});
});

http.listen(3000, function () {
	console.log('listening on*: 3000');
});

- 앞의 소스와 유사합니다. 단지 소켓 이벤트를 받는 부분에 집중해주세요
- 처음 접속했다면 socket.broadcast를 이용하여 자신을 제외한 다른 클라이언트들에게 접속 여부를 알립니다.
- socket.on('disconnect') : 해당 함수로 소켓 통신이 끝났는지 확인 할 수 있습니다. 이곳에다 위와같은 작업을 추가합니다.

3. 확인

node index.js

localhost:3000

서버를 가동하고 localhost:3000으로 접속해주세요. 그리고 이후에 창을 하나더 띄워주세요

다시 브라우저 하나를 닫아주세요.

위와같이 나왔다면 성공입니다 :)

다음은 접속 유저의 닉네임을 추가해보도록 하겠습니다.

블로그 이미지

리딩리드

,
donaricano-btn

1. 이벤트 발생

앞의 예제에서 socket.io를 연동하고 클라이언트에서 채팅창을 구현했습니다. 또한 클라이언트가 소켓을 연결헀을때 서버 로그로 접속되는것 까지 확인했습니다. 이번에는 클라이언트에서 발생한 이벤트를 서버로 전달하겠습니다.

예를들어 클라이언트 입력폼에 메시지를 submit 하면 서버에서 해당메시지를 받는지 확인하겠습니다.

2. 클라이언트 설정

index.html

<body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(function () {
        var socket = io();
        $('form').submit(function(e){
          e.preventDefault(); // prevents page reloading
          socket.emit('chat message', $('#m').val());
          $('#m').val('');
          return false;
        });
      });
    </script>
    
  </body>

기존에 작성했던 클라이언트 코드 <script> 부분을 위와같이 추가합니다.
- socket.emit() : 첫번째 변수가 key 값이 됩니다. server 소켓에서 이벤트를 감지할 경우 해당 키값으로 이벤트를 listen 합니다. 두번째 변수는 value 를 전달합니다.

3. 서버설정

index.js

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);

app.get('/', function(req, res){
	res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket) {
	socket.on('chat message', function(msg){
		console.log('message: '+msg);
	})
});

http.listen(3000, function () {
	console.log('listening on*: 3000');
});

- socket.on(): 첫번째 변수는 키값으로 클라이언트에서 소켓 이벤트를 발생시켰을때 연결됩니다. 두번쨰 변수의 함수는 콜백함수로 클라이언트에서 넘어온 변수값을 받습니다.

위와 같이 localhost:3000으로 접속하여 채팅창에 값을 입력후 send를 누루면 서버 창에 log로 저희가 입력한 값들이 출력됩니다. 

4. 브로드캐스트

서버로 받은 메시지를 이젠 다른 클라이언트들이 공유할 수 있도록 브로드캐스트 해보겠습니다.

index.html

 <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(function () {
        var socket = io();
        $('form').submit(function(e){
          e.preventDefault(); // prevents page reloading
          socket.emit('chat message', $('#m').val());
          $('#m').val('');
          return false;
        });
        socket.on('chat message', function(msg){
           $('#messages').append($('<li>').text(msg));
         });
      });
    </script>

  </body>

- socket.on() : 서버에서 요청하는 이벤트를 listen 하는 역할을하며 데이터를 받아와 클라이언트에 노출시키는 작업을 할 수 있습니다.

index.js

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);

app.get('/', function(req, res){
	res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

http.listen(3000, function () {
	console.log('listening on*: 3000');
});

- socket.on(): 다른 소켓(클라이언트)온 이벤트를 처리합니다
- io.emit() : 해당함수를 이용하여 서버에 데이터를 연결된 소켓으로 전달하는 역할을 합니다. 저희가 만들려면 채팅프로그램의 핵심입니다.

node index.js

서버를 활성화 시킨후 localhost:3000 브라우저를 여러개 띄워주세요.

- 위 화면처럼 입력을 하면 양쪽의 브라우저에서 모두 노출되나요? 그렇다면 성공입니다. :)

5. 나를 제외한 클라이언트에게 브로드캐스팅

socket.broadcast.emit('chat message', 'hi');

socket.broadcast: 나를 제외한 다른 사람에게만 브로드캐스팅합니다. 

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);

app.get('/', function(req, res){
	res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
	socket.broadcast.emit('chat message', 'hi');
});

http.listen(3000, function () {
	console.log('listening on*: 3000');
});

- 저희가 작업한 server 소스중에 이벤트 리슨하는부분을 위와같이 변경해주세요.
이후에 localhost:3000을 하나씩 띄운다면 기존에 있던 창에 hi가 출력되는것을 볼 수 있습니다.

블로그 이미지

리딩리드

,
donaricano-btn

1. socket.io 구성

socket.io는 두 가지로 구성됩니다

- socket.io : 서버에서 사용되는 모듈 입니다.

- socket.io-client: 브라우저에서 사용되는 모듈입니다.

2. socket.io 설치

npm을 이용해 설치하겠습니다

npm install socket.io

1) 서버 socket.io

index.js

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);

app.get('/', function(req, res){
	res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket) {
	console.log('a user connected');
});

http.listen(3000, function () {
	console.log('listening on*: 3000');
});

- socket.io를 require 받은 후 .on 함수로 connection 이벤트를 연결합니다.
- socket.io 변수로 http 객체를 전달받았습니다.
- 이제 서버로 들어오는 socket연결들을 리스닝 할 수 있습니다.

2) 클라이언트 socket.io-client

    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io();
    </script>

-  </body> 태그 이전에 위와같이 등록합니다. 
- io() 함수가 글로벌하게 등록되었습니다. 클라이언트에 로드되는 모든 브라우저 소켓에 작동합니다
- 만약 글로벌보다는 로컬버전으로 사용하게 하고싶다면 node_modules/socket.io-client/dist/socket.io.js연결하면 됩니다
- io() 안에 특정한 url을 등록하지 않았습니다. url을 등록하지 않았다면 자동적으로 서버 호스트로 연결합니다.

3. socket.io 실행

위의 과정을 했다면 노드서버를 다시 작동시키겠습니다.

node index.js

 그리고 브라우저 창에 localhost:3000으로 접속합니다.

localhost:3000으로 접속했을때 커맨드라인에 a user connected 가 출력됬다면 소켓이 연결된 것입니다. 여러 창을 띄워볼까요?

창을 두개 띄웠더니 a user connected 가 두개 생성되었습니다. 

4. socket.io 연결끊기 추가

위 상태에서 브라우저창을 닫으면 터미널에 아무것도 출력되지 않습니다. 이제 소켓연결이 끊어진것도 추가하겠습니다

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);

app.get('/', function(req, res){
	res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket) {
	console.log('a user connected');
	socket.on('disconnect', function() {
		console.log('user disconnected');
	});
});

http.listen(3000, function () {
	console.log('listening on*: 3000');
});

- io.on 함수에 disconnect 이벤트를 추가했습니다

다시 서버를 재가동한후 localhost:3000에 접속했다가 브라우저를 닫아 보겠습니다.

위와같이 연결이 끊겼다고 나오면 성공입니다.

다음에는 드디어 채팅창을 만들어 보도록 하겠습니다. 예전에 c언어로 작성했던 채팅 소스와 비교하니 감개무량합니다 
:)

블로그 이미지

리딩리드

,
donaricano-btn

1. 에디터, 서버와 클라이언트 셋팅

블로그에서 만드는 채팅프로그램은 socket.io 스타터 프로젝트를 재현합니다. 재현하면서 발생하는 문제를 기록하고 프로젝트 마지막에 있는 남은 과제또한 수행하는것이 목적입니다. 

https://socket.io/get-started/chat/

 

Socket.IO — Chat

In this guide we’ll create a basic chat application. It requires almost no basic prior knowledge of Node.JS or Socket.IO, so it’s ideal for users of all knowledge levels. IntroductionWriting a chat ap

socket.io

socket.io를 알고싶다면 저와함께 프로젝트를 조금씩 진행하시기를 추천드립니다.

2. 프로젝트 셋팅

- 에디터: intellij

- OS: 윈도우 10

1) 서버만들기

기본적으로 NPM 을 사용하여 서버를 셋팅하고 서버는 node, express 를 사용합니다.

프로젝트 폴더에 npm 을 설치해주세요.

npm init -y

그리고 express를 설치합니다.

npm install express

express는 노드서버를 만들때 더욱 쉽게 만들수 있는 패키지입니다.

root 디렉토리에 index.js 파일을 하나 만들고 아래와 같이 작성해주세요

var app = require('express')();
var http = require('http').createServer(app);

app.get('/', function(req, res){
  res.send('<h1>Hello world</h1>');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

- app.get('/') : 서버라우터 역할을 합니다. /을 통해서 들어온 요청은 해당 get 함수를 실행시킵니다.
- res.send(): 서버렌더링으로 브라우제어 <h1> 태그를 출력합니다.

mac이라면 터미널을 이용하여 node index.js 를 입력하세요. 윈도우라는 cmd 저는 intellij 터미널에서 입력하겠습니다.

node index.js

위의 이미지처럼 서버가 잘 켜졌나요?
이제 브라우저에 localhost:3000으로 접속해보겠습니다.

위와 같이 브라우저에 표시됬다면 성공입니다. 이젠 Hello world 가 아닌 그럴듯한 채팅 창으로 렌더링 하겠습니다. socket.io 사이트 예제에 있는 마크업을 그대로 복붙하겠습니다. 그전에 root 디렉토리에 index.html 파일을 만들어 주세요.

index.html

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
  </body>
</html>

그리고 node 서버도 해당 파일을 불러서 화면에 렌더링 할수 있도록 index.js 파일도 수정하겠습니다.

index.js

const app = require('express')();
const http = require('http').createServer(app);

app.get('/', function(req, res){
	res.sendFile(__dirname + '/index.html');
});

http.listen(3000, function () {
	console.log('listening on*: 3000');
});

- sendFile() : 노드에서 프로젝트 경로에있는 특정 파일을 찾아 클라이언트 브라우저로 내려주는 역할을 합니다. 
__dirname은 루트경로를 의미합니다.

변경한상태에서 서버를 다시 재가동해주세요. 그리고 다시한번 localhost:3000으로 접속합니다.

위와같이 화면이 나왔다면 성공입니다. 아직까진 어려울게 없네요.
다음 장에서는 드디어 socket,io를 연동해보도록 하겠습니다.

블로그 이미지

리딩리드

,