강동현

매우 간단한 로그인 로직 작성

import { Socket } from "socket.io";
import { ConnectionMapper } from "./connection/ConnectionMapper";
export class SocketHandler {
private connectionMapper: ConnectionMapper;
constructor() {
this.connectionMapper = new ConnectionMapper();
}
public connected(socket: Socket) {
const connection = this.connectionMapper.get(socket);
}
}
import { Socket } from "socket.io";
import { MessageHandlerRegister } from "../message/handler/MessageHandlerRegister";
import { User } from "../user/User";
export class Connection {
public readonly socket: Socket;
public user?: User;
constructor(socket: Socket) {
this.socket = socket;
MessageHandlerRegister.registerMessageHandlers(this);
}
public get authenticated(): boolean {
return this.user !== undefined;
}
}
import { Socket } from "socket.io";
import { Connection } from "./Connection";
export class ConnectionMapper {
private map: Map<Socket, Connection>;
constructor() {
this.map = new Map<Socket, Connection>();
}
public get(socket: Socket): Connection {
var value = this.map.get(socket);
if (value) {
return value;
}
value = new Connection(socket);
return value;
}
public close(socket: Socket): void {
this.map.delete(socket);
}
}
import express from 'express';
import socketIo from 'socket.io';
import { createServer } from 'http';
import express from "express";
import socketIo from "socket.io";
import { createServer } from "http";
import { SocketHandler } from "./SocketHandler";
const PORT = 3000;
......@@ -8,8 +9,10 @@ const app = express();
const server = createServer(app);
const io = new socketIo.Server(server);
io.on('connection', socket => {
console.log('Connected.');
})
const handler = new SocketHandler();
server.listen(PORT, () => console.log(`Listening on ${PORT}`))
io.on("connection", (socket) => {
handler.connected(socket);
});
server.listen(PORT, () => console.log(`Listening on ${PORT}`));
......
import { Connection } from "../../connection/Connection";
import { User } from "../../user/User";
import { LoginMessage } from "../types";
import { MessageHandler } from "./MessageHandler";
export class LoginHandler implements MessageHandler<LoginMessage> {
public handle(connection: Connection, message: LoginMessage): void {
connection.user = new User(message.username);
console.log(`User ${message.username} has logged in!`);
}
}
import { Connection } from "../../connection/Connection";
export interface MessageHandler<T> {
handle(connection: Connection, message: T): void;
}
import { Connection } from "../../connection/Connection";
import { LoginMessage } from "../types";
import { LoginHandler } from "./LoginHandler";
export class MessageHandlerRegister {
static registerMessageHandlers(connection: Connection) {
connection.socket.on("login", (message: LoginMessage) => {
new LoginHandler().handle(connection, message);
});
}
}
export interface LoginMessage {
username: string;
}
export class User {
public readonly username: string;
constructor(username: string) {
this.username = username;
}
}