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를 연동해보도록 하겠습니다.

블로그 이미지

리딩리드

,
donaricano-btn

1. socket.io 란?

- 과거에 모의 프로젝트로 채팅프로그램을 만든적이있다면 socket 통신이란 단어를 들어보았을 겁니다. 서버소켓과 클라이언트 소켓을 만들어 응답과 요청을 실시간으로 처리할 수 있다는 것이 소켓 통신의 핵심요지입니다. 결국은 양방향 통신이 가능하다 입니다. 

(소켓 통신이란 검색하면 정말많이 나오기때문에 따로 다루지는 않겠습니다)

만약 소켓통신을 처음부터 만들게 된다면 꽤나 많은 소스양을 보시게 될겁니다. 서버, 클라이언트 통신의 맺고 끝음을 관리해야되며 소켓의 이벤트 처리 등 신경쓸 부분이 많습니다. 

그러나 이런 수고로움을 덜어줄 소켓 통신 라이브러리가 나오게 되었습니다. 무엇보다 javascript 라는 점이 너무나 매력적인 포인트입니다. 그 소켓 라이브러리가 바로 socket.io 입니다.

https://socket.io/

 

Socket.IO

SOCKET.IO 2.0 IS HERE FEATURING THE FASTEST AND MOST RELIABLE REAL-TIME ENGINE ~/Projects/tweets/index.js var io = require('

socket.io

socket.io를 통해 다양한 웹 서비스를 쉽게 만들어 볼 수 있습니다. 기본적인 채팅 프로그램부터 실시간 데이터를 반영해야되는 그래프까지 양방향 데이터 서비스를 이젠 쉽게 자바스크립트로 만들 수 있습니다.

다음 글에서는 socket.io 페이지에 있는 채팅프로그램을 따라가보도록 하겠습니다.

블로그 이미지

리딩리드

,