WebSockets를 사용하여 클라이언트(휴대기기나 컴퓨터 등)에서 App Engine 인스턴스로의 영구 연결을 만들 수 있습니다. 개방형 연결은 언제든지 클라이언트와 서버 간의 양방향 데이터 교환을 허용함으로써 지연 시간을 단축하고 리소스를 더 효율적으로 사용할 수 있도록 합니다.
WebSockets
RFC 6455에 정의된 WebSockets 프로토콜은 클라이언트와 서버 간의 전이중 통신 채널을 제공합니다. 채널은 'upgrade' 헤더가 있는 HTTP(S) 요청으로 시작됩니다.
WebSockets의 일반적인 사용 사례는 다음과 같습니다.
소셜 미디어 피드, 스포츠 점수, 뉴스, 주가 등의 실시간 이벤트 업데이트
소프트웨어, 콘텐츠 업데이트 등의 사용자 알림
채팅 애플리케이션
협업 편집 도구
멀티플레이어 게임
WebSockets는 추가적인 설정 없이 애플리케이션에서 항상 사용할 수 있습니다.
설정된 WebSockets 연결은 1시간 후에 타임아웃됩니다.
WebSocket 사용 요금은 제한 시간이나 소켓 종료까지의 연결 사용량에 따라 청구됩니다.
WebSockets로 샘플 애플리케이션 실행
이 문서의 코드 샘플에서는 WebSockets로 샘플 애플리케이션을 실행하는 방법을 설명합니다.
기본 요건 및 설정
개발 환경 설정의 안내에 따라 환경과 프로젝트를 설정하고 앱이 구조화되는 방식을 이해합니다.
샘플 앱 클론
샘플 앱을 로컬 머신에 복사한 후 websockets 디렉터리로 이동합니다.
로컬에서 샘플 실행
App Engine에서 샘플 배포 및 실행
세션 어피니티
모든 클라이언트가 WebSockets를 지원하는 것은 아닙니다. 이를 해결하기 위해 많은 애플리케이션은 WebSockets를 지원하지 않는 클라이언트에서 http 장기 폴링으로 대체하는 socket.io와 같은 라이브러리를 사용합니다.
일반적으로 App Engine은 요청을 사용 가능한 인스턴스 간에 균등하게 분배합니다.
하지만 http 장기 폴링을 사용할 때는 특정 사용자의 여러 순차적 요청이 동일 인스턴스에 전달되어야 합니다.
App Engine이 동일 사용자의 요청을 동일 인스턴스에 보낼 수 있도록 하기 위해 세션 어피니티를 사용 설정할 수 있습니다. 그러면 App Engine이 쿠키를 조사하여 동일 사용자가 보낸 요청을 식별하고 해당 요청을 동일 인스턴스에 라우팅합니다.
App Engine에서 세션 어피니티는 최선의 방식으로 실행됩니다. 앱을 개발할 때는 항상 세션 어피니티가 보장되지 않는다고 가정해야 합니다.
다음과 같은 시나리오에서 클라이언트가 대상 인스턴스와의 어피니티를 잃을 수 있습니다.
애플리케이션을 제공하는 인스턴스를 App Engine 자동 확장 처리가 추가하거나 삭제할 수 있습니다. 이 애플리케이션은 부하를 재할당할 수 있으며, 대상 인스턴스가 이동할 수도 있습니다. 이 위험을 최소화하기 위해 예상 부하를 처리하기 위한 최소 인스턴스 수를 설정해야 합니다.
대상 인스턴스가 상태 확인에 실패할 경우 App Engine은 세션을 정상 인스턴스로 이동합니다. 상태 확인 및 맞춤설정 옵션에 대한 자세한 내용은 분할 상태 확인을 참조하세요.
유지보수 또는 소프트웨어 업데이트를 위해 인스턴스가 재부팅될 때 세션 어피니티가 손실됩니다. App Engine 가변형 환경 VM 인스턴스는 매주 다시 시작됩니다.
세션 어피니티는 보장되지 않으므로 연결이 끊어진 경우에만 socket.io 및 기타 라이브러리를 사용하여 HTTP 장기 폴링으로 대체해야 합니다. 스테이트풀(Stateful) 애플리케이션을 빌드하는 데 세션 어피니티를 사용해서는 안 됩니다.
세션 어피니티 사용 설정 및 중지
기본적으로 세션 어피니티는 모든 App Engine 애플리케이션에 대해 비활성화되어 있습니다.
세션 어피니티는 애플리케이션의 버전 수준에서 설정되며 배포 시 사용 설정되거나 중지될 수 있습니다.
App Engine 버전에 세션 어피니티를 사용 설정하려면 app.yaml 파일에 다음 항목을 추가합니다.
network:session_affinity:true
업데이트된 app.yaml과 함께 버전이 배포되면 새 요청이 동일 인스턴스에서 제공되기 시작합니다. 단, 해당 인스턴스가 사용 가능한 상태여야 합니다.
세션 어피니티를 중지하려면 app.yaml 파일에서 항목을 삭제하거나 값을 false로 설정합니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-04(UTC)"],[[["\u003cp\u003eWebSockets offer a full-duplex communication channel between clients and servers, enabling real-time data exchange and reducing latency.\u003c/p\u003e\n"],["\u003cp\u003eTypical use cases for WebSockets include real-time event updates, user notifications, chatting applications, collaborative editing tools, and multiplayer games.\u003c/p\u003e\n"],["\u003cp\u003eSession affinity, which routes requests from the same user to the same instance, can be enabled in App Engine to accommodate HTTP long polling as a fallback for clients not supporting WebSockets.\u003c/p\u003e\n"],["\u003cp\u003eSession affinity in App Engine is not guaranteed and should be used only for allowing fall back from libraries such as socket.io, and not for stateful applications.\u003c/p\u003e\n"],["\u003cp\u003eSession affinity can be enabled or disabled at the version level in App Engine by modifying the \u003ccode\u003eapp.yaml\u003c/code\u003e file, ensuring that clients have cookies enabled for it to function.\u003c/p\u003e\n"]]],[],null,["# Creating persistent connections with WebSockets\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nGo Java Node.js PHP Python Ruby .NET Custom\n\nYou can use WebSockets to create a persistent connection from a client (such\nas a mobile device or a computer) to an App Engine instance. The open\nconnection allows two-way data exchange between the client and the server at any\ntime, resulting in lower latency and better use of resources.\n\nWebSockets\n----------\n\nThe WebSockets protocol, defined in [RFC 6455](https://tools.ietf.org/html/rfc6455),\nprovides a full-duplex communication channel between a client and a server. The\nchannel is initiated from an HTTP(S) request with an \"upgrade\" header.\n\nTypical use cases for WebSockets include:\n\n- Real time event updates, such as social media feeds, sports scores, news, or stock market prices\n- User notifications, such as software or content updates\n- Chatting applications\n- Collaborative editing tools\n- Multiplayer games\n\nWebSockets are always available to your application without any additional setup.\nOnce a WebSockets connection is established, it will time out after one hour.\nUsage of the WebSocket is [billed by connection usage](/appengine/pricing#managing)\nuntil timeout or socket termination.\n\n\u003cbr /\u003e\n\nRunning a sample application with WebSockets\n--------------------------------------------\n\nThe code samples in this document describe how to run a sample application with\nWebsockets.\n\n\n### Prerequisites and setup\n\nFollow the instructions in\n[Setting Up Your Development Environment](/appengine/docs/flexible/setting-up-environment)\nto set up your environment and project, and to understand how apps are structured.\n\n### Clone the sample app\n\nCopy the sample apps to your local machine, and navigate to the `websockets`\ndirectory:\n\n\u003cbr /\u003e\n\n### Run the sample locally\n\n\u003cbr /\u003e\n\n### Deploy and run the sample on App Engine\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nSession affinity\n----------------\n\nNot all clients support WebSockets. To work around this, many applications\nuse libraries such as [socket.io](http://socket.io/) that fall back on http long\npolling with clients that don't support WebSockets.\n\nApp Engine typically distributes requests evenly among available instances.\nHowever, when using http long polling, multiple sequential requests from a given\nuser need to reach the same instance.\n\nTo allow App Engine to send requests by the same user to the same instance,\nyou can enable session affinity. App Engine then identifies which requests\nare sent by the same users by inspecting a cookie and routes those requests to\nthe same instance.\n| **Important:** App Engine applications must always be tolerant of session affinity interruptions, particularly because all App Engine instances are periodically restarted. Enabling session affinity can also limit the effectiveness of App Engine's load balancing algorithms and can cause your instance to become overloaded.\n\nSession affinity in App Engine is implemented on a best-effort basis. When\ndeveloping your app, you should always assume that session affinity is not guaranteed.\nA client can lose affinity with the target instance in the following scenarios:\n\n- The App Engine autoscaler can add or remove instances that serve your application. The application might reallocate the load, and the target instance might move. To minimize this risk, ensure that you have set the minimum number of instances to handle the expected load.\n- If the target instance fails health checks, App Engine moves the session to a healthy instance. For more information about health checks and their customization options, see [Split health checks](/appengine/docs/flexible/reference/app-yaml#updated_health_checks).\n- Session affinity is lost when an instance is rebooted for maintenance or software updates. App Engine flexible environment VM instances are restarted on a weekly basis.\n\nBecause session affinity isn't guaranteed, you should only use it to take\nadvantage of the ability of `socket.io` and other libraries to fall back\non HTTP long polling in cases where the connection is broken. You should never\nuse session affinity to build stateful applications.\n\nEnabling and disabling session affinity\n---------------------------------------\n\n| **Important:** To take advantage of session affinity, cookies must be enabled for all clients that are accessing your application, such as end-user web browsers and API clients. Clients without cookie support cannot take advantage of session affinity.\n\nBy default, session affinity is disabled for all App Engine applications.\nSession affinity is set at the version level of your application and can be\nenabled or disabled on deployment.\n\nTo enable session affinity for your App Engine version, add the following\nentry to your `app.yaml` file: \n\n network:\n session_affinity: true\n\nOnce the version is deployed with the updated app.yaml, new requests will start\nserving from the same instance as long as that instance is available.\n\nTo turn off session affinity, remove the entry from your [`app.yaml` file](/appengine/docs/flexible/reference/app-yaml#network_settings),\nor set the value to false: \n\n network:\n session_affinity: false"]]