1. 개요
아래 깃허브의 예제 step-04는 Socket.IO가 이전 버전으로 약간의 수정이 필요하다. 서버 프로그램을 먼저 실행 시킨후 클라이언트가 방번호를 제공하면서 접속하면 해당 방을 만들어 주고 최대 2명 까지만 접속을 허용한다.
https://github.com/googlecodelabs/webrtc-web
2. 서버 프로그램
예제 step-04에서 > npm install 을 하여 필요한 모듈을 설치한다.
다음 서버 프로그램 index.js 파일을 실행한다. index.js 소스를 약간 수정하였다.
// Socket.IO는 브라우저와 서버 간의 실시간, 양방향, 그리고 이벤트 기반 통신을
// 가능하게 해주는 라이브러리입니다.
//npm install socket.io
'use strict';
var os = require('os');
var nodeStatic = require('node-static');
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
var path = require('path')
let numClients=0;
//public이라는 폴더의 클라이언트 접근 허용 (미들웨어)
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', (socket)=> {
console.log('connection...');
//to log server messages on the client
function log() {
var array = ['Message from server:'];
array.push.apply(array, arguments);
socket.emit('log', array);
console.log('emit log message>>'+array);
}
socket.on('message', function(message) {
log('Client said: ', message);
console.log('Client said: '+ message);
// for a real app, would be room-only (not broadcast)
socket.broadcast.emit('message', message);
});
socket.on('create or join', function(room) {
console.log('Received request to create or join room ' + room);
log('Received request to create or join room ' + room);
var clientsInRoom = io.sockets.adapter.rooms.get(room);
numClients = clientsInRoom ? clientsInRoom.size : 0;
console.log("before join clientsInRoom="+clientsInRoom);
console.log("before join numClients="+numClients);
if (numClients === 0) {
socket.join(room);
log('Client ID ' + socket.id + ' created room ' + room);
socket.emit('created', room, socket.id);
console.log("room "+room+" has created and joined by first client");
} else if (numClients === 1) {
log('Client ID ' + socket.id + ' joined room ' + room);
io.sockets.in(room).emit('join', room);
socket.join(room);
socket.emit('joined', room, socket.id);
io.sockets.in(room).emit('ready');
} else { // max two clients
socket.emit('full', room);
console.log("max user is execeeded!!!");
}
clientsInRoom = io.sockets.adapter.rooms.get(room);
numClients = clientsInRoom ? clientsInRoom.size : 0;
log('Room ' + room + ' now has ' + numClients + ' client(s)');
console.log('Room ' + room + ' now has ' + numClients + ' client(s)');
});
socket.on('ipaddr', function() {
var ifaces = os.networkInterfaces();
for (var dev in ifaces) {
ifaces[dev].forEach(function(details) {
if (details.family === 'IPv4' && details.address !== '127.0.0.1') {
socket.emit('ipaddr', details.address);
}
});
}
});
});
server.listen(3000, () => {
console.log('listening on :3000');
});
3. 클라이언트 프로그램
step-04 하단에 public 폴더를 만들고 그 아래에 css js socker.io 3개의 폴더를 만든다.
index.html 을 public 아래에 복사하고 main.css를 public/css/로, main.js를 public/js/ 아래에 복사한다.
npm install로 설치하면 node_modules라는 폴더가 만들어지는데 node_modules/socket.io/client-dist 아래에 있는
모든 파일을 public/socket.io/ 아래에 복사를 한다. 다음은 index.html 파일이다.
<!DOCTYPE html>
<html>
<head>
<title>Realtime communication with WebRTC</title>
<link rel="stylesheet" href="css/main.css" />
</head>
<body>
<h1>Realtime communication with WebRTC!!</h1>
<script src="socket.io/socket.io.js"></script>
<!-- <script src="https://cdn.socket.io/socket.io-1.0.0.js"></script> -->
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script src="js/main.js"></script>
</body>
</html>
다음은 main.js파일이다.
'use strict';
var isInitiator;
window.room = prompt("Enter room name:");
//var socket = io.connect();
var socket = io();
if (room !== "") {
console.log('Message from client: Asking to join room ' + room);
socket.emit('create or join', room);
}
socket.on('created', function(room, clientId) {
console.log('created');
isInitiator = true;
});
socket.on('full', function(room) {
console.log('Message from client: Room ' + room + ' is full');
});
socket.on('ipaddr', function(ipaddr) {
console.log('Message from client: Server IP address is ' + ipaddr);
});
socket.on('joined', function(room, clientId) {
console.log('joined');
isInitiator = false;
});
socket.on('log', function(array) {
console.log.apply(console, array);
});
반응형