본문 바로가기

WIL

[WIL]7주차

이번 프로젝트에서 본인은 SMTP 프로토콜과 SSE통신을 활용해서 프로젝트에 필요한 기능들을 구현했다. 

 

SMTP란 인터넷에서 이메일을 보내기 위해서 이용되는 프로토콜이다. SMTP는 모든 문자가 7bit ASCII로 되어 있어야 하기 때문에 문자 표현에 8비트 이상의 코드를 사용하는 언어나 첨부파일 같은 경우에 마임(MIME)이라는 방식으로 7비트로 변환되어 전달된다. 

SMTP를 활용할 때 네이버메일을 활용했는데, 계정에서 SMTP 관련 설정을 해주고, 

InternetAddress[] receiverList = new InternetAddress[1];
receiverList[0] = new InternetAddress(requestDto.getEmail());
// SMTP 발송 Properties 설정
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", HOST);
props.put("mail.smtp.port", PORT);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", HOST);
props.put("mail.smtp.auth", "true");
// SMTP Session 생성
Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator(){
    protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
        return new javax.mail.PasswordAuthentication(MAIL_ID, MAIL_PW);
    }
});

// Mail 조립
Message mimeMessage = new MimeMessage(mailSession);
mimeMessage.setFrom(new InternetAddress(MAIL_ID));
mimeMessage.setRecipients(Message.RecipientType.TO, receiverList);
// 메일 제목
mimeMessage.setSubject("인증 메일입니다.");
// 메일 본문 (.setText를 사용하면 단순 텍스트 전달 가능)
mimeMessage.setText(randStr+"를 입력해주세요");
// Mail 발송
Transport.send(mimeMessage);

과 같은 코드를 사용해서 메일을 전송할 수 있었다. 해당 메일은 회원가입시 이메일 인증하기 위해서 구현하였으며, 최초에 그냥 서버에 저장하는 형식으로 구현했지만, 팀원이 redis를 활용해서 재구성했다. 

 

SSE(Server Sent Event) 통신은 서버가 클라이언트에게 데이터를 전송하는 통신이다. 웹소켓과 달리 SSE는 단방향 통신이라 구현할 때 웹소켓은 바로 받았는지 여부를 통신보낼 수 있지만 SSE는 그렇지 못하기 때문에 검증하는 과정이 필요하다. 

해당 기능은 음식점 사장이 주문이 들어왔을 때 주문이 들어왔음을 알리는 알람, 음식점 사장이 고객에게 배달이 완료되었음을 알리는 알람 기능을 구현하기 위해서 사용하였으며, 

const getCookieValue = (key) => {
    const cookies = document.cookie.split('; ').reduce((acc, cookie) => {
        const [k, v] = cookie.split('=');
        acc[k] = v;
        return acc;
    }, {});

    return cookies[key] || null;
};

$(document).ready(function(){
    const authorization = getCookieValue('Authorization');
    console.log(authorization)

    if (authorization) {
        let URL = host + '/test/subscribe/'+authorization;
        console.log("------------------------------")
        console.log(URL)

        const eventSource = new EventSource(URL);

        //const eventSource = new EventSource('http://localhost:8080/test/subscribe/'+authorization);
        //1 대신 cookie의 헤더 정보를 가져와서 userid를 집어넣어준다.
        eventSource.addEventListener('sse', event => {
            let jobj = JSON.parse(event.data).content
            if(jobj != null) alert(jobj)
        });
    }
});

해당 코드를 대부분의 html들이 상속받는 main.js에 넣어서 해당 페이지가 로드될 때마다 Cookie에서 사용자 토큰을 가져와서 subscribe를 한 상태에서 주문이 들어오거나 배달이 완료되면 주문정보를 기반으로 원하는 사용자의 username을 기반으로 알람을 보내는 방식으로 구현하였다.

'WIL' 카테고리의 다른 글

[WIL] 8주차  (0) 2023.10.02
[WIL]6주차  (0) 2023.09.18
[WIL] 4주차  (0) 2023.09.11
[WIL]3주차  (0) 2023.09.03
[WIL]2주차  (0) 2023.08.27