728x90
방 만들어서 실시간 시간 공유
클라이언트
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Client</title>
</head>
<body>
<button onclick="create()">Create</button>
<input type="text" name="room-code" id="room-code">
<button onclick="join()">Join</button>
<button onclick="leave()">Leave</button>
<p><b id="last-msg"></b></p>
<script>
const ws = new WebSocket("ws://localhost:8005");
ws.onopen = function (event) {
}
ws.onmessage = function (event) {
console.log(event.data);
document.getElementById("last-msg").innerText = event.data;
let messageElem = document.createElement('div');
messageElem.textContent = event.data;
document.getElementById('messages').prepend(messageElem);
}
function create() { ws.send('{ "type": "create" }'); }
function join() {
const code = document.getElementById("room-code").value;
const obj = { "type": "join" , "params": { "code": code }}
ws.send(JSON.stringify(obj));
}
function leave() {
const code = document.getElementById("room-code").value;
const obj = { "type": "leave" , "params": { "code": code }}
ws.send(JSON.stringify(obj));
}
</script>
</body>
<div id="messages"></div>
</html>
index.js
const WebSocket = require('ws');
var DB = require('./db.js');
var CREATE = require('./create.js');
var db = new DB();
const wss = new WebSocket.Server({ port: 8005 });
const maxClients = 5;
let rooms = {};
let joinuserTemp = 1;
db.LogMsg();
wss.on('connection', function connection(ws)
{
ws.user = genKey(5);
var create = new CREATE();
console.log(ws.user);
ws.on('message', function message(data) {
console.log(JSON.parse(data));
const obj = JSON.parse(data);
const type = obj.type;
const params = obj.params;
switch (type) {
case "create":
//create(params);
create.create(params,rooms, ws, db);
break;
case "join":
join(params);
break;
case "leave":
leave(params);
break;
default:
console.warn(`Type: ${type} unknown`);
break;
}
});
function generalInformation(ws) {
let obj;
if (ws["room"] != undefined)
{
obj = {
"type": "info",
"params": {
"room": ws["room"],
"no-clients": rooms[ws["room"]].length,
}
}
}
else
{
obj = {
"type": "info",
"params": {
"room": "no room",
}
}
}
ws.send(JSON.stringify(obj));
}
function create(params) {
const room = genKey(5);
console.log("room id : " + room);
rooms[room] = [ws];
ws["room"] = room;
generalInformation(ws);
}
function genKey(length) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for (let i = 0; i < length; i++) {
result += characters.charAt(
Math.floor(Math.random() * characters.length));
}
return result;
}
function join(params) {
const room = params.code;
if (!Object.keys(rooms).includes(room)) {
console.warn(`Room ${room} does not exist!`);
return;
}
if (rooms[room].length >= maxClients) {
console.warn(`Room ${room} is full!`);
return;
}
rooms[room].push(ws);
ws["room"] = room;
generalInformation(ws);
var UserList = "";
for(let i = 0; i < rooms[room].length; i++)
{
UserList += "User : " + rooms[room][i].user + " \\n";
}
joinuserTemp += 1;
obj = {
"type": "info",
"params": {
"room": ws["room"],
"UserList" : "TTT : " + UserList
}
}
for(var i = 0; i < rooms[room].length; i++)
{
rooms[room][i].send(JSON.stringify(obj));
}
}
function leave(params) {
const room = ws.room;
if(rooms[room].length > 0)
{
rooms[room] = rooms[room].filter(so => so !== ws);
ws["room"] = undefined;
if (rooms[room].length == 0)
{
close(room);
}
}
function close(room) {
if(rooms.length > 0)
rooms = rooms.filter(key => key !== room);
}
}
});
create.js
var LOOPS = require('./Loop.js');
var CREATE = function ()
{
console.log("CREATEReadInfo");
};
CREATE.prototype.LogMsg = function ()
{
console.log("CREATEConnect");
};
CREATE.prototype.generalInformation = function(ws, rooms) {
let obj;
if (ws["room"] != undefined)
{
obj = {
"type": "info",
"params": {
"room": ws["room"],
"no-clients": rooms[ws["room"]].length,
}
}
}
else
{
obj = {
"type": "info",
"params": {
"room": "no room",
}
}
}
ws.send(JSON.stringify(obj));
}
CREATE.prototype.create = function(params , rooms , ws , db) {
const room = this.genKey(5);
console.log("room id : " + room);
rooms[room] = [ws];
ws["room"] = room;
this.generalInformation(ws, rooms);
var loops = new LOOPS();
loops.StartLoops(params , rooms , ws , db, room);
}
CREATE.prototype.genKey = function(length) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for (let i = 0; i < length; i++) {
result += characters.charAt(
Math.floor(Math.random() * characters.length));
}
return result;
}
module.exports = CREATE;
db.js
var DB = function ()
{
console.log("ReadInfo");
};
DB.prototype.LogMsg = function ()
{
console.log("DBConnect");
};
module.exports = DB;
Loop.js
var LOOPS = function ()
{
let loop;
let fps = 1;
let gameloopTimeCount = 0;
this.LogMsg = function ()
{
console.log("GAMELOOPS");
};
this.StartLoops = function(params , rooms , ws , db , room)
{
loop = setInterval(() => {
gameloopTimeCount += 1;
console.log("Looping : " + gameloopTimeCount);
obj = {
"type": "info",
"params": {
"room": ws["room"],
"loopTimeCount" : gameloopTimeCount
}
}
for(var i = 0; i < rooms[room].length; i++)
{
rooms[room][i].send(JSON.stringify(obj));
}
} , 1000/fps);
}
};
module.exports = LOOPS;
'코딩캠프 > 내일배움캠프' 카테고리의 다른 글
[ WIL ] 01.09~14 9주차 (0) | 2023.01.15 |
---|---|
[ TIL ] 01.13(금) 45일차 (0) | 2023.01.13 |
[ TIL ] 01.11(수) 43일차 (0) | 2023.01.11 |
[ TIL ] 01.10(화) 42일차 (0) | 2023.01.10 |
[ TIL ] 01.09(월) 41일차 (0) | 2023.01.09 |