더북(TheBook)

다음으로 채팅방 아이디로 새로운 소켓을 생성하고 메시지를 받아들일 준비를 한다.

socket = new WebSocket(socketEndPoint + roomId);

socket.onmessage = function(e) {

    addMessage(JSON.parse(e.data));

}

이때 이미 생성된 소켓이 있으면 이전 소켓은 닫는다.

if (socket != null) {
    socket.close();
}

입력 창에 메시지를 입력한 후 전송하면 소켓을 통해 메시지가 전달된다.

socket.send(JSON.stringify({
    "room_id": currentRoomId,
    "content": msgBox.val()
}));

다음은 완성된 클라이언트 화면이다.

그림 9-11 클라이언트 화면
신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.