컴퓨터(Computer Science)/네트워크, Network

HTTP vs Web Socket

게임이 더 좋아 2023. 1. 13. 10:30
반응형
728x170

통신에는 여러 종류가 있고 HTTP 통신과 WS(Web Socket) 통신이 존재함

 

정의

HTTP:

HyperText Transferr Protocol

HTTP는 어떤 Format을 써야하는지, 어떻게 Transmit해야하는지, 어떤 Action을 취해야하는지를 포함해서 통신함

URL을 이용하여 통신함

Stateless Protocol

요청 (Request)- 응답(Response)의 포맷을 띄는 통신 형태

 

 

Action 

주로 쓰이는 Action 정의

 

Method
Description
GET Retrieves the information identified by the URI. Can only retrieve data and should have no other effect.
HEAD Same as GET, but only retrieves the headers and no message body.
POST Submits an entity to the identified resource; the client may suggest the resource to handle the request.
PUT Replaces all current representations of the target resource with the request payload.
DELETE Deletes the specified resource.
CONNECT Establishes a tunnel to the server identified by the URI.
OPTIONS Describes the communication options for the target resource.
TRACE Performs a message loop-back test along the path to the target resource.
PATCH Applies partial modifications to a resource.

 

 

 

 

URL

Uniform Resource Locator

URL : 특정 리소스의 경로를 가리키는 문자열

scheme://domain:port/path?query_string#fragment
  • scheme: The protocol used to access the resource (e.g. "http" or "https").
  • domain: The domain name or IP address of the server hosting the resource.
  • port: The port number to connect to (this is optional and is usually omitted if the default port is being used).
  • path: The location of the resource on the server.
  • query_string: Data passed to the server in key-value pairs(this is optional)
  • fragment: Section of the resource (this is optional)

 

예를 직접 들어보자면

https://www.example.com/path/to/resource?key1=value1&key2=value2#section1
  • scheme is "https"
  • domain is "www.example.com"
  • port is not specified
  • path is "/path/to/resource"
  • query_string is "key1=value1&key2=value2"
  • fragment is "section1"

 

 

Format

 

Header와 Body 존재

 

 

Header

 

Header를 통해 여러가지 request에 부가적인 설명을 추가할 수 있음

주로 쓰는 헤더에 들어가는 Field 들

 

Field Name Description
Content-Type Indicates the type of data in the message body, such as "application/json" for JSON data or "image/jpeg" for a JPEG image.
Authorization Used to provide authentication information to the server, such as a user name and password or an API token.
User-Agent Provides information about the client software and version.
Accept Indicates the types of content that the client is able to understand.
Accept-Language Indicates the preferred language of the client.
Cookie Used to send cookies stored on the client to the server.
Referer Contains the address of the previous web page from which a link to the currently requested page was followed.
Cache-Control used to set cache settings for a requested resource
Connection used to indicate the desired behavior of the connection after the response is sent
Content-Length Indicates the size of the message body in bytes.

 

예시

curl --location --request GET 'http://www.example.com/path/to/resource?key1=value1&key2=value2' \
--header 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0' \
--header 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
--header 'Accept-Language: en-US,en;q=0.5' \
--header 'Cookie: session_id=1234567890; user_prefs=color=blue' \
--header 'Referer: https://www.example.com/previous/page' \
--header 'Cache-Control: max-age=0'

Body

 

바디는 어떠한 형식의 데이터가 들어가게 됨

Content-Type을 정해주는 것이 대부분임

 

주로 쓰는 바디에 들어가는 Field들

 

Content Type Description
application/x-www-form-urlencoded Data encoded in the format of key-value pairs separated by an '&' character, as in a query string.
application/json Data encoded in JSON format
application/xml Data encoded in XML format
multipart/form-data Data that include files, commonly used for file uploads

 

예시

curl --location --request POST 'http://www.example.com/path/to/resource' \
--header 'Content-Type: application/json' \
--data-raw '{
    "key1": "value1",
    "key2": "value2",
    "key3": {
        "subkey1": "subvalue1",
        "subkey2": "subvalue2"
    }
}'

 

Status Code

Request가 아닌 Response에서는 추가적으로 Status Code가 추가됨

status code로 여러가지 요인을 알 수 있음

 

Status Code Description
200 OK The request was successful, and the server has returned the requested data.
201 Created The request was successful and a new resource was created as a result.
204 No Content The request was successful, but there is no additional information to send back, typically used in DELETE request.
400 Bad Request The request was malformed or invalid.
401 Unauthorized The request requires user authentication.
403 Forbidden The server understands the request, but it refuses to authorize it.
404 Not Found The server can't find the requested resource.
405 Method Not Allowed The method used in the request is not supported by the resource.
406 Not Acceptable The server can only generate a response that is not accepted by the client.
415 Unsupported Media Type The server refuses to accept the request because the payload format is in a format not supported
500 Internal Server Error The server encountered an unexpected condition that prevented

 

 

 

WS:

 

Web Socket

Stateful Protocol

Connection 유지

=> 실시간 통신 가능, 낮은 latency

Web Socket은 full-duplex 통신 채널을 제공

많은 브라우저에서 제공됨 => 웹 통신에 최적화, overhead 적게 발전함

 

 

**Full-Duplex 통신 채널이란

통신 채널의 한 종류로써 양 측의 데이터를 송신과 수신이 자유로운 데이터 채널을 의미함

=> 원래는 통신할 때 Collision Detection을 하여 송신, 수신의 충돌을 감지하여 해당 채널에서 하나의 동작만 가능했음

=> 전화와 같이 말하면서 듣기도 가능한 통신을 의미함

 

 

 

 

HTTPS vs WSS?

뒤에붙는 S 는 Secure로  SSL을 적용하는 통신 

다를 것이 별로 없음

 

특징

 

HTTP:

(Connectionless) 비연결형 통신

=> Request - Response 할 때마다 Connection을 Open 하고 Close 하는 작업을 거침

 

이러한 오버헤드를 줄이기 위해

HTTP/1.1에서는 persistent와 keep-alive 라는 기능을 추가함

HTTP/2 에서는 server push 라는 기능을 추가함

 

 

 

WS:

(Connection) 연결형 통신

처음에 Establishing 할 때는 HTTP를 이용함

Connection 된 이후에는 TCP 방식 통신

 

 

 


 

HTTP 통신에 Port가 필요가 없는 이유

 

통신을 하려면 대부분 포트가 필요하지만 Internet에서는 Port가 포함되지 않은 채로 통신함

대부분의 웹 브라우저, 클라이언트들은 Default 포트를 쓰기 때문임

80번 포트를 Default 로 사용하며 HTTPS의 경우에는 443 포트를 사용함

특별히 포트를 따로 뚫어놓은 경우에만 URL에 포트를 추가해서 요청함

http://www.example.com:8080/

 

 

 

Socket과 Web Socket의 차이

 

Socket은 비교적 Low Level의 통신할 때 사용함

Socket은 여러가지 프로토콜을 이용하여 통신 가능(TCP, UDP)

 

Web Socket은 특정 프로토콜만 이용하여 실시간 통신을 하는 경우가 대부분

HTTP 통신에 쓰인 많은 기반 기술을 같이 사용함(TCP/IP) 형태의 통신이 대부분

Web Socket은 full-duplex 통신 채널을 제공함

 

요약하면 Socket이 조금 더 큰 개념이고 Low-level이고

Web Socket이 High-level 개념임

 

**Full-Duplex 통신 채널이란

통신 채널의 한 종류로써 양 측의 데이터를 송신과 수신이 자유로운 데이터 채널을 의미함

=> 원래는 통신할 때 Collision Detection을 하여 송신, 수신의 충돌을 감지하여 해당 채널에서 하나의 동작만 가능했음

=> 전화와 같이 말하면서 듣기도 가능한 통신을 의미함

 

 


 

 

참고링크

 

https://ably.com/topic/websockets-vs-http

https://ws-pace.tistory.com/104

https://pearlluck.tistory.com/335

 

반응형
그리드형

'컴퓨터(Computer Science) > 네트워크, Network' 카테고리의 다른 글

VPC 간의 통신  (0) 2023.04.01
사전 정의된 IP들  (0) 2023.01.21
WAF, Web Application Firewall  (0) 2023.01.04
Bastion Host, BH, 배스쳔 호스트  (0) 2022.12.08
Dedicated Game Server  (1) 2022.12.07