
웹소켓을 활용한 프로젝트를 진행하면서 생각보다 웹소켓에 대해서 잘모르고 진행하고 있다는 생각이 들었다.
웹소켓을 사용하기 이전까지 HTTP 프로토콜을 활용한 통신은 클라이언트가 서버에 요청을 보내면 서버가 응답하는 단방향 통신 방식이었다. GET, POST 등
그러나 웹소켓은 양방향 통신을 제공하는 컴퓨터 통신 프로토콜 중 하나이다.
웹소켓을 활용해서 실시간 데이터를 교환할 수 있고 활용 예시로는 채팅, 게임, 주식 시장 데이터 업데이트처럼 실시간 데이터 전송이 필요한 경우에 사용한다.
나같은 경우에는 upbit api를 활용하기 위해서 웹소켓을 활용했다.
해당 프로젝트에서는 okhttp3 의 WebSocketListener 추상클래스를 활용했다.
추상클래스이므로 상속받아 커스텀 웹소켓리스너 클래스를 만들때는 추상메서드를 정의해줘야 한다.
아래는 okhttp3 의 WebSocketListener 추상클래스 이다.
/*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import okio.ByteString
abstract class WebSocketListener {
/**
* Invoked when a web socket has been accepted by the remote peer and may begin transmitting
* messages.
*/
open fun onOpen(webSocket: WebSocket, response: Response) {
}
/** Invoked when a text (type `0x1`) message has been received. */
open fun onMessage(webSocket: WebSocket, text: String) {
}
/** Invoked when a binary (type `0x2`) message has been received. */
open fun onMessage(webSocket: WebSocket, bytes: ByteString) {
}
/**
* Invoked when the remote peer has indicated that no more incoming messages will be transmitted.
*/
open fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
}
/**
* Invoked when both peers have indicated that no more messages will be transmitted and the
* connection has been successfully released. No further calls to this listener will be made.
*/
open fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
}
/**
* Invoked when a web socket has been closed due to an error reading from or writing to the
* network. Both outgoing and incoming messages may have been lost. No further calls to this
* listener will be made.
*/
open fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
}
}
WebSocketListener 라이브러리에서 제공되는 메서드들은 크게 5가지로
1. onOpen 메서드는 파라미터로 웹소켓과 리스폰스를 받고 있다.
해당 메서드에서 구현한 내용은 웹소켓 연결이 열렸을 때 호출되며 성공적으로 연결이 되면 실행한다.
2. onMessage 는 오버로딩 되어 있는 것을 볼 수 있다.
웹소켓을 받는 것은 같지만 하나는 String 하나는 ByteString을 받고 있다.
해당 메서드에서 구현한 내용은 메시지가 수신되었을 때 실행하는 부분이다.
3. onClosing
웹소켓과 int타입의 코드, string 이유를 받고 있다.
더 이상 들어오는 메시지가 없을 때 닫히기 시작하면서 실행되는 내용이다.
4. onClosed
웹소켓과 int타입의 코드, string 이유를 받고 있다.
더 이상 들어오는 메시지가 없고 커넥션이 완전히 끊겼을 때 호출된다.
해당 메서드 호출 이후로는 더 이상 이 리스너에 대한 호출을 받지 않는다.
5. onFailure
예외가 발생했을 때 실행되는 코드
++
HTTP :
HTTP 통신은 HTML이라는 문서를 운반하기 위한 프로토콜로,
HTTP를 사용한 통신은 클라이언트가 서버에 Request를 요청하면 웹서버가 그 요청에 Response하는 형태이다.
웹 서버는 응답을 보낸 후 웹 브라우저와의 연결을 끊는다.
웹소켓:
기존 HTTP 통신은 잦은 연결을 맺고 끊는 과정 때문에 서버 효율성이 떨어지게 되었다.
이를 해결하기 위해 외부 플러그인이 항상 필요했는데, 2014년부터 HTML5에 웹 소켓을 포함하게 되었다.
웹소켓은 Response를 보낸 후에도 연결을 끊지 않고 연결 상태를 그대로 유지한다.
전이중통신채널 :
데이터를 보내는 장치와 받는 장치가 데이터를 송수신할 수 있는 방식을 의미한다.
'Spring' 카테고리의 다른 글
Spring JPA JPQL - argument type mismatch ERROR (0) | 2024.01.12 |
---|

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!