강동현

방 접속시 유저 정보 업데이트

import { RoomData } from "../room/types";
import { UserData } from "../user/types";
export interface Message {
readonly type: string;
......@@ -24,9 +25,24 @@ export class RoomLeaveMessage implements Message {
constructor() {}
}
export class RoomInfoMessage implements Message {
readonly type = MessageType.ROOM_INFO;
constructor(public userdata: UserData[]) {}
}
export class RoomUserUpdateMessage implements Message {
readonly type = MessageType.ROOM_USER_UPDATE;
constructor(
public state: "added" | "updated" | "removed",
public userdata: UserData
) {}
}
export class MessageType {
static readonly LOGIN = "login";
static readonly ROOM_LIST = "room_list";
static readonly ROOM_JOIN = "room_join";
static readonly ROOM_LEAVE = "room_leave";
static readonly ROOM_INFO = "room_info";
static readonly ROOM_USER_UPDATE = "room_user_update";
}
......
import { Connection } from "../connection/Connection";
import { v4 as uuidv4 } from "uuid";
import { RoomData } from "./types";
import {
Message,
RoomInfoMessage,
RoomUserUpdateMessage,
} from "../message/types";
import { UserData } from "../user/types";
export class Room {
public readonly uuid: string;
......@@ -19,6 +25,12 @@ export class Room {
}
public connect(connection: Connection): void {
// TODO: 더 나은 인증 처리
const user = connection.user;
if (user === undefined) {
return;
}
if (
this.connections.includes(connection) ||
this.connections.length >= this.maxConnections
......@@ -28,13 +40,27 @@ export class Room {
this.connections.push(connection);
connection.room = this; // TODO: 더 나은 관리
this.broadcast(new RoomUserUpdateMessage("added", user.getData()));
var users: UserData[] = [];
this.connections.forEach((con) => {
if (con.user !== undefined && connection !== con) {
users.push(con.user.getData());
}
});
connection.send(new RoomInfoMessage(users));
}
public disconnect(connection: Connection): void {
const index = this.connections.indexOf(connection);
if (index > -1) {
if (connection.user !== undefined && index > -1) {
this.connections.splice(index, 1);
connection.room = undefined;
this.broadcast(
new RoomUserUpdateMessage("removed", connection.user.getData())
);
}
}
......@@ -47,6 +73,14 @@ export class Room {
};
}
public broadcast(message: Message, except?: Connection): void {
this.connections.forEach((connection) => {
if (connection !== except) {
connection.send(message);
}
});
}
public close(): void {
if (!this.closed) {
this.connections.forEach((connection) => this.disconnect(connection));
......
import { UserData } from "./types";
export class User {
public readonly username: string;
constructor(username: string) {
this.username = username;
}
public getData(): UserData {
return {
username: this.username,
};
}
}
......
export interface UserData {
username: string;
}