상세 컨텐츠

본문 제목

web 통신 웹소켓 또는 그외 통신 도구 관련

WEB/웹통신 관련

by AlrepondTech 2020. 9. 23. 02:02

본문

반응형

 

 

=================================

=================================

=================================

 

 

HTML WebSocket(웹소켓)이란?

 

자세히osstech 작성카테고리: java 게시일: 07 6월 2014 마지막으로 업데이트 된 날짜: 07 6월 2014 생성일자: 07 6월 2014 조회수: 94

요즘  WebSocket(웹소켓)이라는 단어를 많이 들을 수 있다.

대체 WebSocket이 무엇일까?

 

WebSocket은 HTTP의 단점을 보완하기 위하여 등장했다. 

1991년 발표된 HyperText Transfer Protocol인 HTTP는 오랜 시간 우리 곁에 있었다. 

우리의 브라우저 창에는 늘 http:// 가 따라 붙고 있으니 말이다.

그러나, 이 오랜 시간 사용된 HTTP는 Client-Server간 접속을 유지하지 않으며,

Client-Server간 한 번에 한 방향으로만 통신이 가능한 half-duplex이다.

점차 서로간 주고받는 데이터의 량이 많아지면서 half-duplex로 인한 성능 저하는 피할 수 없게 되었다.

또한 HTTP는 지나치게 많은 헤더 데이터를 가지고 있다.

특히 Client(브라우저)가 요청을 보내지 않아도 Server가 데이터를 보내주는 기능의 구현에 있어서는

많은 고민이 있어왔지만 HTTP의 근본적 메커니즘 탓에 한계가 있어왔다.

그래서 HTML5에 이 WebSocket이 포함되었다.

이름처럼, 이  WebSocket을 사용하면 더 이상 ActiveX를 사용하지 않고도 TCP/IP 소켓통신을 구현할 수 있다.

또한 네트워크의 과부하를 줄이고 애플리케이션의 반응성을 높일 수 있게 된다.

앞서 말한 HTTP 헤더 크기 문제도 800byte에서 수 kbyte의 헤더 크기를 가지고 있는 HTTP와 달리 

WebSocket은 수 byte 수준으로 압축이 가능하다.

물론 WebScoekt이 HTTP를 대체하는 것은 아니다.

다만 HTTP가 적합치 않은 메세징, 트랜잭션 및 애플리케이션 특성 상 트래픽이 높고 지연시간이 낮은 환경에서 유용하다.

RMI(Rremote Method Invocation), JMS(Java Messaging Service), 

XMPP(Extensible Messaging and Presence Protocol) 등이 그 예이다.

현재 주요 브라우저 별 WebSocket 지원여부는 아래와 같다. (최신 브라우저는 대개 지원함)

  • IE : 11.0
  • IE Mobile : 10.0
  • Firefox : 29.0 ~
  • Chrome : 34.0 ~
  • Safari : 7.0
  • iOS Safari : 7.0 

WebSocket은 http://www.websocket.org/echo.html 에서 체험해 볼 수 있다.

 

 

=================================

=================================

=================================

 

 

출처: http://msdn.microsoft.com/ko-kr/library/windows/apps/xaml/hh994396.aspx

 

WebSockets을 사용하여 연결 샘플(XAML)

언어: HTML | XAML

 

Windows 런타임 환경에 제공된 Windows.Networking.Sockets 네임스페이스를 사용하여 Windows 스토어 앱이 대기 시간이 짧고 보안이 유지된 실시간 양방향 통신에 WebSocket을 사용하여 데이터를 보내고 받을 수 있도록 합니다.

WebSocket이란?

WebSocket 프로토콜은 웹을 통해 클라이언트와 서버 간의 신속하고 보안이 유지된 양방향 통신을 위한 메커니즘을 정의합니다. 데이터가 전이중 단일 소켓 연결을 통해 즉시 전송되므로 두 끝점에서 실시간으로 메시지를 보내고 받을 수 있습니다. WebSocket은 실시간 게임, 인스턴트 소셜 네트워크 알림, 주식 또는 날씨 정보의 최신 디스플레이, 안전하고 빠른 데이터 전송이 필요한 기타 앱을 포함하는 Windows 스토어 앱에서 사용하는 데 적합합니다.

WebSocket 연결을 설정하기 위해 클라이언트와 서버 간에 특정 HTTP 기반의 핸드셰이크가 교환됩니다. 교환이 성공하면 이전에 설정된 TCP 연결을 사용하여 응용 프로그램 계층 프로토콜이 HTTP에서 WebSocket으로 "업그레이드"됩니다. 업그레이드된 후에 HTTP는 완전히 무시되고 WebSocket 연결이 닫힐 때까지 두 끝점에서 WebSocket 프로토콜을 사용하여 데이터를 보내거나 받을 수 있습니다.

중요  서버가 WebSocket 프로토콜을 사용하지 않는 한 클라이언트는 WebSocket을 사용하여 데이터를 전송할 수 없습니다. 서버가 WebSocket을 지원하지 않으면 다른 데이터 전송 방법을 사용해야 합니다.

Windows 8에서는 클라이언트와 서버의 WebSocket 사용을 모두 지원합니다. Windows.Networking.Sockets네임스페이스는 Windows 스토어 앱에서 클라이언트가 사용할 두 가지 유형의 WebSocket 개체 즉,MessageWebSocket 및 StreamWebSocket을 정의합니다. 아래 표에서는 두 가지 유형의 WebSocket에 대해 설명합니다.

MessageWebSocketStreamWebSocket

메시지가 지나치게 크지 않은 일반적인 시나리오에 적합합니다. 큰 파일(예: 사진 또는 영화)을 전송하는 시나리오에 적합합니다.
전체 WebSocket 메시지가 수신되었다는 알림을 사용하도록 설정합니다. 각 읽기 작업에서 메시지 섹션을 읽을 수 있습니다.
UTF-8 및 이진 메시지를 모두 지원합니다. 이진 메시지만 지원합니다.
UDP 소켓(DatagramSocket)과 유사합니다. TCP 소켓(StreamSocket)과 유사합니다.

 

대상 개발자 그룹

VB/C#/C++ 및 XAML을 사용하여 WebSocket을 통해 웹 서비스에 연결하는 Windows 런타임 앱을 만들려고 하는 개발자

다음 정보는 C++/XAML로 작성한 Windows 런타임 앱 및 C# 또는 Visual Basic으로 작성한 .NET Framework 4.5 사용 앱에 적용됩니다.

JavaScript 및 HTML로 작성한 Windows 런타임 앱용 웹 서비스에 WebSocket을 통해 연결하는 방법에 대한 자세한 내용은 WebSocket을 사용하여 연결(JavaScript를 사용하는 Windows 런타임 앱)을 참조하세요.

이 섹션의 내용

항목설명

MessageWebSocket을 사용하여 연결하는 방법 MessageWebSocket을 사용하여 웹 서버로 데이터를 보내고 받기 위한 요구 사항 및 특정 단계를 자세히 설명합니다.
StreamWebSocket을 사용하여 연결하는 방법 StreamWebSocket을 사용하여 웹 서버로 데이터를 보내고 받기 위한 요구 사항 및 특정 단계를 자세히 설명합니다.
고급 WebSocket 컨트롤을 사용하는 방법 고급 소켓 컨트롤을 사용하여 WebSocket 개체에서 옵션을 설정하는 방법을 설명합니다.
TLS/SSL을 통해 WebSocket 연결의 보안을 유지하는 방법 TLS(전송 계층 보안)/SSL(Secure Sockets Layer)을 통해 WebSocket 연결의 보안을 유지하는 방법을 설명합니다.

 

유사 기능 및 관련 기능에 대해 알아보기

섹션설명

네트워크 접근 권한 값을 구성하는 방법 네트워크 격리 기능에 대해 소개하고 네트워크 격리 접근 권한 값을 구성하여 Windows 스토어 앱에 대한 네트워크 액세스를 완전히 제어하는 방법을 설명합니다.
소켓을 사용하여 네트워크에 연결 소켓을 사용하여 네트워크 리소스로 데이터를 보내고 받기 위한 요구 사항 및 특정 단계를 자세히 설명합니다.
네트워킹 지원 추가 앱에 네트워킹 지원을 추가하는 방법에 대해 설명합니다.
네트워크 연결 문제 해결 및 디버그 연결 문제 해결에 도움이 되는 제안 사항과 정보를 제공합니다.

 

관련 항목

기타네트워크 접근 권한 값을 구성하는 방법C# 또는 Visual Basic으로 작성한 Windows 런타임 앱용 로드맵C++로 작성한 Windows 런타임 앱용 로드맵참조MessageWebSocketStreamWebSocketWindows.Networking.Sockets샘플WebSocket 샘플

 

 

=================================

=================================

=================================

 

 

출처: http://www.codeigniter-kr.org/etc_qna/view/2160/page/1

웹소켓 이용해 보신 분 계신가요?

채팅서버를 기반으로 학습게임 사이트를 만들려고 합니다.
처음에는 ajax 와 db를 연동해서 연습을 했는데 동시접속자가 많을 경우에는 이 방법은 비추천이라고 하더군요. 
웹소켓으로 구현하는 방법을 알게 되었는데요. 
혹시 실무에서 이용해 보신 분 계시면 서버 1대당 동시접속자수라던가 다른 장단점을 좀 알려 주시면 감사하겠습니다. 

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

웹소켓이래 봤자 기존 소켓통신을 웹에서 받을 수 있게끔 정의한것에 지나지 않습니다. (핸드셰이크 처리가 추가된..)
당연히 소켓 컨넥션에 수많은 절차를 거치는 http통신 보다 서버 부하에 대해서는 훨씬 유연합니다.

채팅을 어떤식으로 서비스할지나 부하량에 따라 서버 아키텍쳐가 다르게 설계되기 때문에 동시접속자 수의 예측은 힘든데요.

서버는 32비트 환경에서 개발해도 이론적으로 65535개의 소켓을 받을 수 있습니다.
이는 일반적인 운영체제가 저정도로 제한 하고 있기 때문도 있지만, TCP/IP의 헤더 구조상 하나의 아이피에 사용될 수 있는 포트 수가 65535개를 벗어나지 못하기 때문입니다. 물론 서버운영체제로 바꾸고, 네트워크 장비를 복수로 취하는 방법으로 컨넥션을 늘릴 수 있습니다.

컨넥션을 많이 받을 수 있더라도 로직의 처리속도 혹은 IO가 늦어지면 사실상 저정도 동시접속은 처리할 수 없구요. 처리 속도 향상을 위해서 클라이언트 별 쓰레드를 줄이거나 휴식중인 소켓을 죽이거나 등등 별별 시도를 다 하면 동시접속자 수는 1대당 10만 이상 받을 수 있겠지만 이건 오랜 경험을 통해 나오는 노하우라서..

결론은 개발자 역량에 따라서 매우 많이 받을 수 있을겁니다.

요즘은 무작정 1대당 많이 받는 형태보다 하드웨어만 늘리면 알아서 클라우딩되는 형태의 개발을 많이 취합니다. 유지보수의 스트레스를 돈으로 해결하는 쪽으로 많이 기울고 있습니다. (웹서버 구조가 그렇듯이..)

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

아주 쉽게 가고 스트레스 없이 가실꺼면 node.js + socket.io 추천드립니다.

음 저의 경우는 실시간 접속현황 + 강제 벤 + 쪽지보내기 + 실시간 글 알림 + 실시간 댓글알림하여서 

동시접속 5000 여명 정도 커버 치고있습니다(다만 좀 버벅이는 감이 없지않아있습니다)

워낙에 페이지 이동이 많다보니 socket이 접속되고 끈기고 접속되고 끈기고하다보이.. 5천명까지는 힘들게 버티고 

2000명까지는 어느정도 여유롭게 버팁니다(q8300 + 램 8기가 + 하드 500기가 서버 입니다, 100메가 데디)


제가 서버 자원 최대로 활용해서 최대 4600명까지 안정권으로 소켓 연결을 유지 시킨적이있습니다(근데 동시에 몇백명이 접속을 끈으면 서버 부하 심각하게 걸렸던게 함정)

음 서론이 너무 길었네요

node.js를 추천드린게 제가 느끼는 장단점 입니다.

장점
- node.js는 자바스크립트 엔진이기에 자바스크립트를 아신다면 좀 거부감이 덜하실껍니다. 진짜 자바스크립트 입니다.
- 비동기 방식을 선호하신다면 가볍게 서버개발을 하실수있습니다.
- socket.io라는 멀티플랫폼 웹소켓서버 이용하시면 좀더 쉽게 소켓서버 운영가능하십니다

단점
- node.js 의경우는 디버그하기가 참 거시기합니다( 오류있는 구문 실행하기전까지 절대 오류 안남. 오류 있는 구문이 실행됬을때 서버 뻗어버림)
- socket.io라는 모듈은 편하지만 동시접속이 많으면 많을수록 렉이 발생 함. 네이글알고리즘을 끄고 v8엔진을 수정보고 가비지 콜렉션을 제어하면 빨라진다지만 이것도 미지수임 실전을 통해 겪어야 가능함.

대충 이정도이네요. 제 기준점에선 node.js로 소켓서버 운영하셔도 괜찮다 싶을정도입니다

단 동시접속이 너무 많지않다는 가정하에요 ^^

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

 

=================================

=================================

=================================

 

 

출처: http://yourland-textcube.blogspot.kr/2013/01/websocket-pure-streaming-ajax.html

 

2013년 1월 26일 토요일

WebSocket 아니라 Pure Streaming Ajax 가 답

 

Http 프로토콜은 한번 요청을 보고 응답을 받는 것을 기본으로 한다.
네트워크 비용이 말도 안되게 비싸던 시절 만들어진 규약이 그렇다.
그 넷 비용을 획기적으로 낮추는 것이 웹이 활성화되는 결정적인 역할 중 하나다.

Http에서는 뭔가 할 수 있는 것이 없었으나
2000년 초반 XmlHttpRequest라는 것이 ActiveX 형식으로 IE에서 지원되면서
Dynamic HTML에서 통신요소가 깔끔하게 정리되어 정말 유용했었다.

그런데 브라우저들은 보안에 매우 취약하여 웬만한 자원접근은 막아두었다.
심지어 프린터까지...

부정적 활용에 대해 제약을 걸었으나 제약은 제약인지라
모든 긍정적 쓰임도 차단된다.

Http가 tcp/ip에 기반한 Socket 위에서 구현된 규약이라 없으나
보안이란 명목으로 접속중이라도 서버와 클라이언트가 대화하기 곤란하다.
XMLHttpRequest는 HttpClient의 일종이다.

그래서 웹소켓websocket이 대두 되었으나 여러모로 아랫단 소켓과 자잘한 문제들이
다시 대두되는 번거로움이 있다.

짧은 데이터야 ajax든 iframe으로 돌아도 문제될 것이 없다.
그러나 긴..형태의 데이터라면..

그런데 생각해보면 매우 간단한 방법이 있다.

1. Ajax api에 대화만 허용하면 된다.
즉 여러번 메시지를 주고받으면 된다는 것이다.
다른 보안 제약은 그대로 유지해도 좋다.(파일시스템접근제약 등...)

2. response를 streaming해주면 된다.
현재는 responseText는 streaming가 아니다. 물론 ResponseXML도 streaming일 수 없다.
오로지 한꺼번에 다 읽어야 한다.

둘다 socket에 있는 기능이다.
이 두가지면 번거롭게 websocket운운하지 않아도 간단히 해결된다.

서버측에는 엄청난 라이브러리들이 있어서 streaming 기반 통신 API가 널렸다.
HttpClient류에서는 InputStream OutputStream을 바로 참조할 수 있다.
그러나 클라이언트측(브라우저들)에는 너무 심한 제약으로 구현의 제약 뿐만 아니라
streaming으로 처리해야하는 다양한 데이터처리에 bottle neck역할만 한다.

Http는 한번 보내고 한번 받는 것이 기본룰이라 될 수가 없다.
그래서 그 복잡한 websocket이야기가 나오는 것인지..
그렇게되면 Http에서 처리하는 것들(도메인,계정,쿠키,보안..기타등등...)

그렇다면, 왜 이름이 웹소켓이면서 http서버로 바로 접속하면 안되는지..
이또한 http서버들의 구현문제

 


이문제는 protocol... 규약이 제약.
socket하나 얻자고 클라이언트에 java applet 환경을 강요하는 것은 말도 안된다.
(자바가 브라우저에서 실패한 요소 중 하나이다.)
flash는 상대적으로 가볍다고 해도, 모바일이 대세인시대에
flash도 java와 동일한 문제가 발생한다.
오로지 브라우저에서 지원해야 한다.

WebSocket은 정말 궁여지책으로 나온 것이다.
client 브라우저들은 거짐 준비가 된 것 같다.
다만 서버사이드가 표준이라하기엔 다양한 구현이 나와버렸다.
http://en.wikipedia.org/wiki/Comparison_of_WebSocket_implementations

개인적인 생각이지만 위의 두가지 기능만 제공된다면
어떤 작업이 안되는지 궁금할 정도다.

만일 별개의 서버로 간다면..
jWebSocket 이 보여주듯, 수많은 중복구현이 불가피할 것이다.

HTTP2.0도 나올때가 되지 않았나?

window8 의 경우 StreamWebsocket 이란 걸 제공한다는데..
cross browsing-html5 의 이야기를 하는데
오로지 자기지향으로 달리는 것 같아 답답하다..

어쨌던 당장 XMLHTTPRequest에서 stream을 읽을 수 있다면
복잡한 것이 없다.

도중에 통신을 끊지 않고, 메시지를 보낼 수 있다면 더할 나위 없다.

통신되는데, 뭐가 문제야.. 데이터는 문제없다.
------------
문제가 되는 지점은 chatting 형..... 즉 다자간 동기대화형 application이다.
구지 socket이어야 하는 이유지... 주된 영역이 아니라 할말이 없다.

여튼 5개 브라우저와 톰캣으로 간단한 chatting 예제를 돌려보았으나..
Safari는 되지도 않았고(tomcat7과 safari는 맞지 않단다. nio와 맞지 않는다는데..)
같은 IP라서 그런지.. 브라우저에 상관없이
커넥션을 몇개를 생성하건 한놈만 응답을 받는다.
subprotocol 관련된 것인지.. 싶기도 하고.
server에서 IP단위로만 구분하는지..... 참 어렵다.
추가적인 다른 작업이 필요한건지...

서버사이드도 짧지 않은 이야기가 진행중이다.
올해(2013)에 모두 선보이게 될 것 같은데
annotation 기반 POJO Bean 경향으로 다가오게 될 것 같다.

지금 당장 어찌해야 한다면, atmosphere를 이용해야 할 듯.
atmosphere..... 이건 또 오로지 maven이군.
2013-01-31.
-------
atmosphere 로 간단한 채팅예제를 해 보았다.
Window7에서 safari를 제외한 Chrome,IE10,Opera,FireFox는 잘 되었다.
safari만의 문제가 아니라 mac의 전체가 아직 websocket을 지원하지 않는다.
예를 들어 vmware에 osx를 설치후 chrome으로 접속해도 마찬가지고
아이패드3에서 safari,chrome 접속도 마찬가지.

톰캣용 예제의 문제점은 없었다.
다만 문자열에 " "로 감싸져서 왔다. 왜 그런지는 모르겠다.

Websocket 2013년 어느 시점부터 java WAS들에 모두 장착되어 배포될 것으로 보이는데
양방향(full-duplex) 통신이다보니  활용영역이 ajax와는 비교할 수 없을 정도로
다양할 것이다.
용도에 따른 적절한 패턴으로 활용되어야 할 것이다.
2013-02-03
--------
HTTP2.0이 2014년에 표준이 개발될 것이라고 한다.
Google의 SPDY가 수용될 것이라고 한다.
spdy는 밑단에서 브라우저와 웹서버만 되는 것인지..
websocket와 같은 클라이언트의 쉬운 api는 없다.. 있을 것 같은데..

Websocket 은 java was가 지원하더라도
웹서버는 그런 기능이 마련되지 않아서 proxy를 세워 해결한다고 하는데...
kaazing 상용으로 잘 나가는 듯 하다.
2013-02-06
----------------------

 

 

=================================

=================================

=================================

 

 

출처: http://knight76.tistory.com/1466


아래 스펙을 기준으로 삼아서 공부.
http://www.whatwg.org/specs/web-socket-protocol/

키포인트는 바로 아래 헤더이다. 나머지 secure 한 부분이 있긴 하지만...

Connection : Upgrade

Upgrade:WebSocket


통신은 이렇게 한다. http handshake 하고 나서, 데이터는 시작을 알리는 헤더 0x00 정보 다음와 마지막을 의미하는 0xff 사이에 두어 통신한다. 그리고, 0x00 0xff 는 tcp close를 의미한다. 

내 생각엔  handshake와 통신 주고받는 법, 끊기.. 이게 websocket의 다인것 같다.. 
 


(참조 : http://warmcat.com/_wp/2010/11/01/libwebsockets-html5-websocket-server-library-in-c/)
 

 




웹 브라우져가 언제든지 소켓처럼 쓸 수 있다. 

(참조 : http://java.sys-con.com/node/1315473)

 



 


특별히 대단한 기술은 아지만, 다양한 사람들이 모여 하나의 spec를 정하고 이에 맞게 구현하고 있다는 점에서 인정해야 할 것 같다. 생각보다 단순해서 놀랬음.. ^^


참조 : http://cometdaily.com/2008/07/04/html5-websocket/

 

 

=================================

=================================

=================================

 

 

출처: http://openyou.egloos.com/3082617

소개

기존소켓과 다르게 handshake(악수?)를 하는 부분이 있습니다.

- 내가 웹소켓 클라이언트니 서버는 알아서 잘 대해줘잉~ 하고 요청하면 서버는 오호라 니녀석이 웹소켓이구나 알았으~~ 하고 응답을 해주는 과정입니다.(단순한건데 데이타로 주고받고 하니 괜히 어려워보이는것이니 두려워마시고~~)

http://www.codeproject.com/Articles/531698/Introduction-to-HTML-WebSocket

 

게임샘플

http://www.codeproject.com/Articles/314965/SpaceShoot-A-multiplayer-game-in-HTML5

-- 서버코드는 dll로 되어있으니 reflector로 열어보시던지 하시공... ( 열어보니 추천할만한 소스는 아닙니다. 직접 구현하세용)

서버 웹소켓 통신 구현방법은

https://developer.mozilla.org/en-US/docs/WebSockets/Writing_WebSocket_servers

https://developer.mozilla.org/en-US/docs/WebSockets/Writing_WebSocket_server

대용량 서버를 구현하려면 제블로그 http://openyou.egloos.com/2469442 링크를 참고하셔서 구현하세욧~

(SocketAsyncEventArgs 란 녀석을 사용하는 패턴으로 서버를 구현하면 대용량 소켓서버를 구현할 수 있답니다. 성능짱입니다)

 

handshake가 끝나고 나서 데이타 decoding하는 부분이 쬐금 봐야할 부분이네요

http://derod.blogspot.kr/2012/04/html5-websocket-server-using-c.html 이 링크에 코드가  잘 되어있네요

int second = bytes[1] & 127; // AND 0111 1111 이렇게 마스킹을 한 결과값이 126,127 인지에 따라 메시지의 길이필드가 몇자리 인지가 결정된다고 합니다.

 

WCF 4.5에서 웹소켓 지원

http://www.codeproject.com/Articles/341413/What-s-new-in-WCF-4-5-WebSocket-support-Part-2-of

출처:HTML5 WebSocket Server/Client

 

 

=================================

=================================

=================================

 

 

 

 

반응형

 

 

728x90

 

 

 

츌처: http://cometdaily.com/2008/07/04/html5-websocket/

A recent set of HTML5 discussions are changing the course of Comet. First, a recap of the last two years of Comet: With long-polling we set the bar to cross-browser push. With XHR streaming and ActiveXObject(’htmlfile’) we raised it to cross-browser streaming. With SSE we’ve been trying to raise the bar to native, cross-browser streaming. And there we’ve sat, hoping that browser vendors actually implement the latest SSE spec.

I say we’ve been selling ourselves short. All this time pushing for a native server->client streaming transport, but we still lack client->server streaming, and anything resembling a standard transport for bi-directional communication. The Holy Grail of Comet development has always been native browser support of a full-duplex, single-connection communication’s channel, otherwise known as a TCP socket. But we’ve been mired down in hacks so long that we’ve lost the vision.

No Longer. The HTML5 specification now offers WebSocket, a full-duplex communications channel that operates over a single socket. I have been listening closely, and in some cases contributing, to the process of ensuring that WebSocket will:

  • Seamlessly traverse firewalls and routers
  • Allow duly authorized cross-domain communication
  • Integrate well with cookie-based authentication
  • Integrate with existing HTTP load balancers
  • Be compatible with binary data

The API of WebSocket is very straightforward. You create a WebSocket and point it at a url:

var conn = new WebSocket("ws://www.example.com/livedemo")

Then you attach three callbacks:

conn.onopen = function(evt) { alert("Conn opened"); }
conn.onread = function(evt) { alert("Read: " + evt.data); }
conn.onclose = function(evt) { alert("Conn closed"); }

And finally, you can send upstream data with a simple function call:

conn.send("Hello World")

The browser will perform an HTTP handshake with the target web server to determine support, and then a direct stream will be exposed via the onread and send functions. The uri scheme “ws://” is used for WebSocket connections, and the “wss://” URI scheme is for secure WebSocket connections.

After the handshake, bi-directional framed communication ensues. Each frame can be either binary or text, thus allowing for swapping the encoding mid-stream. You can find more information about the protocol itself at the network section of the whatwg HTML5 draft page

While the HTML5 specification is not in a finalized stage, the first public draft was published by the W3C in January 2008, and browser vendors have already began targeting features in the specification. The idea of putting a duplex channel into the spec is not a new one; the TCPConnection API and protocol was initially drafted more than two years ago. Unfortunately there were many significant problems with TCPConnection that held back browser adoption. Ian Hickson, the editor of the HTML5 specification, tackled these problems head on and under his guidance the standard has evolved to a usable state with WebSocket. About this new feature, Mr. Hickson comments:

“I’m looking forward to seeing Web Socket implemented in browsers, as I think it’s going to enable all kinds of realtime applications like chatting, remote controls, and the like, without the ridiculous hacks authors have to use today.”

Comet

WebSocket in a browser is terrific because it drastically cuts down the complexity of the Comet server by an order of magnitude. What’s more though, it provides a straightforward, understandable API to JavaScript developers. The most important part of the specification is that developers can wrap their heads around the API in about five seconds. That’s because it looks so much like a socket.

If the future prospect of a native WebSocket isn’t enough good news, I am proud to announce that the Orbited project has implemented WebSocket for all major browsers, today. We do this by communicating over various Comet transports with the browsers, then performing the WebSocket handshake with the remote server, and proxying data in between. This means that today you can write a WebSocket server and application, start Orbited up, and be on your way. Tomorrow, you won’t need to change any of your server or client code whatsoever. Your application will fall forward to the native implementation of WebSocket for improved performance.

TCPSocket

The single most voiced criticism to this specification has been that a WebSocket isn’t quite the same as a raw TCP socket, because a WebSocket server needs to understand a specific handshake in order for browsers to connect directly, and as such a WebSocket can’t connect to existing servers. If we did allow raw TCP sockets in the browser, a malicious site could cause any visitors to open up a TCP connection to an SMTP server, for instance, turning a casual web visitor into a spambot. There are many variations on this scenario, but the general problem is that a raw socket connections in a browser will allow any sites that a user visits to access network services as if they were the user, in the same network security context as the user. We need to therefore make this an opt-in process or we’ll catch existing servers off-guard. Furthermore, very few protocols have any kind of cross-domain authorization or security mechanisms built in. If we were to allow raw TCP, then we would be opening all manner of cross-site security holes. We could fix these by limiting TCP connections to the origin domain and port, (meaning a direct sockets back to the webserver only) but that would limit any usefulness the TCP socket could provide.

I fully understand the criticism though; Earlier this week I discussed exactly why having a raw socket in the browser is so desirable. You could, for instance, quickly prototype a Gmail clone using a raw socket, an IMAP client, and an XMPP client in the browser.

We have a clear problem then: Direct access to existing network servers could greatly simplify application architecture, but due to security restrictions it’s a non-starter; we absolutely must retrofit each network server with the new WebSocket protocol first. I hope that happens, but we can’t count on it, at least not right away. What we really need is a way to allow the server to opt-in without putting it in the protocol, a way to seamlessly layer access control in front of the back-end server. It turns out that this problem has already been solved for traditional networks. That is, if we have two end-points communicating over TCP, and we need transparent access control in between, then we can use a well known device: A firewall. The beauty of a firewall is that server behind it requires no re-programming, or even re-configuration, yet gains all of the access control/security benefits. What we really need in the browser case, is a custom firewall that can listen for WebSocket connections from the browser, enforce access control, and relay TCP to a back-end server.

That is why Orbited provides this feature under the API name TCPSocket. Orbited is the firewall that sits between the back-end server and the browser. It understands WebSocket protocol for browser communication, and uses whitelist security to accept or reject requests to proxy TCP data to and from a back-end server. That’s right, you can fire up a stock XMPP server, and Orbited, and write the XMPP client entirely in JavaScript. This works cross-browser today. We also offer a binary mode that uses an intermediate encoding to allow the browser to read raw bytes (in the form of JavaScript integer arrays) from a remote server. Here is a diagram of the architecture:

 

 

The Future

Now its up to the browser developers to implement Websocket. I expect some will be very quick on the uptake, while it may take years for others. I expect to see a common pattern emerge where application servers listen to the WebSocket protocol directly from new browsers, but fallback to Orbited’s emulation layer for legacy browsers. The key here is that we don’t have to wait on the browser vendors to get started. We can all develop these WebSocket applications now, and when browsers have native support, we’ll all get a performance boost.

We will probably never get a native (raw) TCP socket in the browser, for the security reasons I outlined. It’s okay though — we can use the firewall pattern I outlined. For more information about installing and configuring Orbited, check out thedocumentation and the getting started section.

 

23 Responses to “Independence Day: HTML5 WebSocket Liberates Comet From Hacks”

  1. Martin Tyler Says: 
    July 4th, 2008 at 2:27 amI’ve not had time yet to look at the spec for this, but you seem to be mainly talking about browsers implementing this. Surely every proxy out there needs to somehow support this.. and what does a server wanting to support it need to do? You, or maybe ‘they’, seem to be presenting it as a browser thing, but it needs support on the server too surely.
  2. Frank Salim Says: 
    July 4th, 2008 at 3:53 amMartin:
    In the article, it says that WebSocket has a protocol designed to work through current proxies. Also, until there are servers supporting WebSocket, Orbited provides backwards compatibility. It has a WebSocket to TCP bridge.
  3. Martin Tyler Says: 
    July 4th, 2008 at 7:30 amThe point of this is to get a socket, not a socket wrapper over comet ‘hacks’ though.With no proxy configured it just makes a straight connection to the server.So this looks just like a much better way to implement a comet server, rather than being able to connect browsers to existing servers.
  4. So anyone know an ETA on browsers supporting this?
  5. The communication isnt a straight socket in that you couldnt connect to an existing server and handle its protocol - the websocket protocol requires specific headers and encoding (although pretty simple).
  6. Ok, I have now read the spec. It uses the existing CONNECT command when going through a proxy, which is intended for SSL connections. Thats something I played around with years ago, but obviously only things like signed applets can make connections to the proxy directly like that.
  7. Metal Hurlant Says: 
    July 4th, 2008 at 8:50 am> We will probably never get a native (raw) TCP socket in the browser, for the security reasons I outlined.You mentioned how neat it would be to have an XMPP client in the browser.
    There’s an open-source project that does just that already:http://www.igniterealtime.org/projects/xiff/It does exist, it has already implemented a lot of the new exciting stuff HTML 5 promises, and it seems peculiar not to learn from it before re-implementing your own flavor of it.
  8. (As a fun aside, the SVG 1.2 draft spec hints at some support for raw TCP socket support. It’s obviously not popular to acknowledge Flash, but their source of inspiration is fairly obvious to anyone who knows the flash APIs and bothers to read their spec http://www.w3.org/TR/2004/WD-SVG12-20041027/)
  9. In truth, with so much of HTML 5’s spec aiming squarely at catching up with Flash functionality, I’m a little bit amazed to see several people behind the spec act in their html 5-related blog posts as if Flash doesn’t exist.
  10. I question the validity of this statement. Every browser with Flash 9 installed has support for raw TCP sockets, and the security model it relies on doesn’t seem to have the security problems you allude to. (it uses socket-served crossdomain.xml files.)
  11. David Davis Says: 
    July 4th, 2008 at 11:41 amI think It should use an observer pattern, so you don’t have to wrap it in a scope.
  12. conn.addListener( ‘open’, this.handleOpen, this );
    conn.addListener( ‘read’ this.handleRead, this );
    conn.addListener( ‘close’, this.handleClose, this );
  13. Jacob Rus Says: 
    July 4th, 2008 at 4:11 pmDavid: It does. Notice that the spec says “WebSocket objects must also implement the EventTarget interface.”
  14. RogerV Says: 
    July 5th, 2008 at 2:51 pmWebSocket as a much superior bi-directional, full-duplex Comet is superb just by itself. Not particularly concerned about trying to get JavaScript in a browser to consume legacy TCP services at the server side.What will be way cool is to keep writing Flex apps today to Adobe’s BlazeDS remoting and messaging abstraction layer, and then down the road get an automatic upgrade in performance when BlazeDS and the FlashPlayer implement WebSocket support.
  15. Finally the W3C has something cooking that is very worthwhile. Otherwise I’d written W3C off as completely hopeless.
  16. I’ve been waiting about five years for the web to get a protocol like WebSocket so that web apps can be implemented to be like distributed rich client messaging-based apps.
  17. David Davis Says: 
    July 6th, 2008 at 2:22 amJacob: Ah I see
  18. Thanks
  19. GregWilkins Says: 
    July 10th, 2008 at 11:30 pmI think this is a huge step backwards. Sockets are simply not the right level of abstraction that we want to expose in javascript. Asynchronous socket programming is hard, with one of my favorite examples being, what does a programmer do with 3 byte of a 6 bytes UTF-8 character?HTTP gives us a lot of support with character encoding and data framing. Many of the so-called hacks take great advantage of this and use the efficient implementations in servers and browsers. Dropping the semantic of the conversation to raw bytes on the wire will just turn js framework developers into async IO programmers and introduce years of instability while they learn how hard that is!.
  20. Currently, nice native code in the browser handles our dataframing and character conversion for us. Websockets is putting that difficult burden onto the javascript framework.
  21. Frank Salim Says: 
    July 11th, 2008 at 12:32 amGreg:
    The authors of the WebSocket spec anticipated this, so WebSocket differs from a TCP socket* in that it is text-based and framed.You will see that the browser hides buffering so that JavaScript only deals with complete frames (which are strings). This makes sending and receiving complete JSON objects or XML very easy. As a matter of fact, this sounds like _exactly_ what you want.
  22. *WebSocket is on top of TCP — it isn’t reinventing the wheel
  23. http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#ws-sd-framing
  24. GregWilkins Says: 
    July 11th, 2008 at 4:48 pmOK, I stand corrected.So this is a messaging system then, were the messages are just strings that can be XML, Json, javascript or something else. Well that I like!
  25. They need to work on there names and descriptions. The name Socket is misleading and their text talks about bytes being available etc.
  26. Orbited Blog » Blog Archive » Talk at OSCON 2008 Says: 
    July 23rd, 2008 at 2:05 pm[...] Independence Day: HTML5 WebSocket Liberates Comet From Hacks [...]
  27. Comet Daily » Blog Archive » Comet Gazing: WebSocket Says: 
    August 7th, 2008 at 10:10 pm[...] time, we’ve asked our contributors the question: “With the recent addition of WebSocket to the HTML 5 recommendation, what impact will this have on your Comet implementation in both the [...]
  28. Orbited Blog » Blog Archive » Our Ancestor’s Secrets: WebSocket Article and Panel Says: 
    October 25th, 2008 at 2:18 am[...] on WebSocket for the Silicon Valley Web Builder blog. He talks about his experiences explaining WebSocket to developers, and how we can “recover our ancestor’s secrets” of good [...]
  29. Comet Daily » Blog Archive » Dojo and WebSocket Says: 
    October 29th, 2008 at 12:04 pm[...] HTML5 defined WebSocket has been gaining in popularity because of its efficient and intuitive approach to Comet. Orbited [...]
  30. John Bailo Says: 
    November 13th, 2008 at 1:12 pmI’ve been trying to avoid Comet altogether until someone came up with a true means to invoke callback functions remotely.
  31. This seems like the real thing — closer to RMI then a “long polling” hack like Comet.
  32. Protocols for the real-time web « Thoughts on technology and social web Says: 
    June 18th, 2009 at 10:49 pm[...] without the long poll overhead. The javascript API is also very simple. COMET can surely take advantage of this and things become more straight forward without hidden iframes and arcane protocols. So can [...]
  33. javamike Says: 
    August 19th, 2009 at 5:51 am> Metal Hurlant : Every browser with Flash 9 installed has support for raw TCP sockets
  34. So does every browser with a java plugin. The focus is to support this functionality without relying on plugins.
  35. testm Says: 
    November 27th, 2009 at 6:32 amHi all,For instance the Orbited demo is blocked here  :( If the whole thing is about using one single point out, then you will fall into priority handling. If the whole thing is on optimizing the stream, then you already have TCP.The standard compatible full featured browser is either a mirage or a myth. You can’t get tons of feature and keep compatible without strong Test Compatibility Kits. There is none madatory for “Web Browser”, to tout : “Compatible Web 2.0″ for instance 
    Hece, the problem to get something as simple as : asynchronous data sending.By putting another layer, you create the illusion of openeing possibilities, but the basic problem is the security model of the whole thing. Chain-o-trust if you preffer …
  36. Don’t get we wrong, I woudl be glad if it succeed, but I doubt it would.
  37. If anycase browser become compatible, be sure firewall will block that.
  38. As javamike said, TCP socket is accessible from either a Java applet (no need to sign as long as you call “home” server) or a flash file … this is possible right now. This spec look like nothing but pushing the TCP API into the webbrowser but not having full benefit of TCP : not straight forward compatibility = need an adapter.
    Applet of Flash are viable solutions right now. There will only be benefit using Websocket when this would be implemented on most Major browser. This will not happen. I don’t think MS will do that.
  39. This whole story about tunneling (or “simulating”) a TCP socket into an HTTP is quite odd to me.
  40. The problem is that I don’t think it will work thru “any” proxy 
  41. Comet Daily » Blog Archive » Is WebSocket Chat Simple? Says: 
    March 2nd, 2010 at 11:25 am[...] WebSocket protocol has been touted as a great leap forward for bidirectional web applications like chat, promising a new era of simple [...]
  42. Don Moir Says: 
    March 15th, 2010 at 1:59 pmMichael, in one of your articles you make the statement that ‘everything sucks’ and it surely does.HTML5 Websockets ? I wonder also how this is actually going to work in some proxy senarios. We have corporations that use proxies that still only support HTTP 1.0. Corporations in general move slowly. It’s probably going to be years and in the meantime we can layer more junk to support this, that, and the other thing.My main thing is to allow cross-domain connections and wide support for it. This allows me to listen on port 80 for socket or HTTP connections quite easily.I am getting older by the minute, faster than normal that is.
  43. If I have to change my server to support websockets, big deal, its not like I don’t have to jump thru hoops already.
  44. These days I use Flash. It sucks too, but provides good support for cross-domain socket or HTTP connections. You can use binary or text data and it is widely available. Of course it is still a plugin and much of it seems to be have written by amatures.
  45. About 6 years ago I started looking at browsers and realtime socket connections. At that time the only realistic approach was to use a java applet. I supported MS JVM and Sun Java 1.1 and up. I used HTML for display purposes as Java was and still is clunky as a display mechanism within a browser. This had to be same domain only as well. There were and still are version and user installation problems with Java. Java 1.6 now offers cross-domain socket connections but am I to ask a naive user to install it ? Sun absolutely blew it by not having a lightweight container for browser applets.
  46. Websocket Chat - Grails websocket Says: 
    September 21st, 2010 at 1:34 am[...] websocket protocol has been touted as a great leap forward for bidirectional web applications like chat, promising a new era of simple [...]
  47. Calling Mr. Client, do you read me? WebSockets to the rescue! | Front end BlogSays: 
    January 7th, 2011 at 5:15 am[...] Protocol: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-03 http://websocket.org http://cometdaily.com/2008/07/04/html5-websocket/ This entry was posted in front end, user experience and tagged comet, HTML5, websocket. Bookmark [...]

 

 

=================================

=================================

=================================

 

 

출처: http://m.mkexdev.net/98

[HTML5] WEB SOCKET (웹 소켓)

POSTED IN 모바일/HTML5 // POSTED AT 2010/09/30 13:44

실시간 (양방향) 통신을 위한 웹의 노력
개인적인 생각으로 HTML5의 새로운 스펙중에 사용자가 가장 흥미로워 한 것이 Canvas 라면

개발자가 가장 흥미로워 한 것은 바로 웹 소켓(Web Socket)이지 않나 싶다

필자 역시 순수 웹 환경에서 연결 지향 양방향 통신을 지원하는 웹 소켓이 가장 눈에 띄는 것 중 하나였다. 과거 순수 웹 환경에서 채팅과 같은 실시간 응용프로그램을 위한 얼마나 많은 시도들이 있었던가...

이제 박물관(?)에서나 볼 법한 숨긴 frame(or iframe) 을 통한 반복적인 재요청은 당시만 해도 웹에서 실시간 효과를 낼 수 있는 참신한 아이디어로 부상한 적이 있었다

이후 Ajax의 등장으로 비동기로 반복 요청을 할 수 있어 그나마 조금은 개선 되었다
그러나 여전히 클라이언트의 비 효율적인 재요청을 피할 수는 없었다

그리고 이후 Comet 의 등장으로 서버 데이터 수신 후 재 요청이 가능해져 불필요한 반복 요청의 비효율성은 개선되었다. 

그러나 이 모든 것은 '폴링(polling)' 방식이다
즉 데이터 수신을 위해 서버가 클라이언트에게 전송해 주는 푸시(push)방식이 아니라 클라이언트가 서버에에게 요청하는 폴링(polling) 방식이었다

비교적 최적의 대안이었던 Comet 역시 무의미한 반복 요청을 피하기 위한 연결유지 기법이 적용되었지만 일정 시간 이후에는 연결을 종료하고 다시 연결해야 한다. 그래서 Comet을 Long-Polling 라 한다

참고: [HTML5] Server-Sent Events

웹의 진정한 실시간 (양방향) 통신, 웹 소켓(Web Socket)의 등장
초기 웹의 탄생 목적은 문서 전달과 하이퍼링크를 통한 문서 연결이었다
웹을 위한 HTTP 프로토콜은 이러한 목적에 매우 부합하는 모델이다
그러나 시대가 변하고 환경이 발전할 수록 웹이 더 이상 문서공유에만 집중할 수 없었다
갈수록 동적인 표현과 뛰어난 상호작용이 요구되었고 이로 인해 여러 새로운 기술이 탄생되었다

플래시(플렉스), 자바애플릿(자바FX), ActiveX , 실버라이트 등을 들 수 있다
하지만 이들은 웹에서 화려한 동작과 뛰어난 상호작용을 보장하지만 순수 웹 환경이 아니라 별도의 런타임을플러그 인 형태로 브라우저에 설치해야 사용 가능하다

HTML5는 그 주요 목적 중 하나인, 플러그 인 없는 일관되고 표준화된 웹 응용 환경이라는 기치하에 많은 참신한 스펙들이 개발되었다. 

그 중 순수 웹 환경에서 실시간 양방향 통신을 위한 스펙이 바로 '웹 소켓(Web Socket)' 이다
웹 소켓은 웹 서버와 웹 브라우저가 지속적으로 연결된 TCP 라인을 통해 실시간으로 데이터를 주고 받을 수 있도록 하는 HTML5의 새로운 사양이다따라서 웹 소켓을 이용하면 일반적인 TCP소켓과 같이 연결지향 양방향 전이중 통신이 가능하다

이와 같은 특징으로 웹에서도 채팅이나 게임, 실시간 주식 차트와 같은 실시간이 요구되는 응용프로그램의 개발을 한층 효과적으로 구현할 수 있게 되었다

웹 소켓과 Ajax 속도 비교
한 일본 사이트에서 웹 소켓과 (Ajax의 통신 객체인) XMLHttpRequest 의 속도 비교를 확인할 수 있는 페이지를 제공하고 있어 화제가 되고 있다
=> http://bloga.jp/ws/jq/wakachi/mecab/wakachi.html (크롬 or 사파리에서 실행)


서버에 존재하는 1,981(공백포함) 길이의 일본문자를 132개로 끊어서 가져오는 데모인데, 각각 웹 소켓과 여러개의 Ajax(병렬 Ajax)를 이용해 각각 호출해서 실행 속도를 비교했다

테스트 할 때마다 실행 속도의 차이가 조금씩 나지만 웹 소켓이 대략 50배 이상 좋은 성능을 보이고 있다



물론 이 사이트의 테스트 시나리오에 따르면, 한번에 모든 문자를 가져오는 것이 아니라 132개로 나눠진 단락들을 가져오는 것이다 보니 한번 연결된 통신 라인으로 데이터만 가져오는 웹 소켓에 비해 매번 헤더정보를 실어서 새로 요청 하는 Ajax가 더욱 느리게 느껴질 수 있다

하지만 이것은 '수 차례 송/수신을 하는 시나리오' 를 가정한 만큼 테스트 시나리오에 문제 제기를 할 필요는 없어 보인다. 웹 소켓을 사용하는 환경의 거의 대부분이 이런 시나리오이기 때문에 더욱 그렇다

어쨋던 확실히 실시간 통신환경에서는 Ajax 보다는 웹 소켓이 월등하다는 것을 알 수 있다

웹 소켓이 필요한 다섯가지 징후?
Peter Lubbers 라는 개발자가 'Five Signs You Need HTML5 WebSockets' 이라는 글을 포스팅 했다
HTML5의 웹 소켓을 이용하면 좋을 5가지 경우를 조목조목 설명하고 있다
뭐.. 결론은 웹 소켓 좋다는 거다 ^^ . 글에서 상단의 Summary 만 가져와 본다

  1. Your web application has data that must flow bi-directional simultaneously.
  2. Your web application must scale to large numbers of concurrent users.
  3. Your web application must extend TCP-based protocols to the browser.
  4. Your web application developers need an API that is easy to use.
  5. Your web application must extend SOA over the Web and in the Cloud.

대략 난잡번역 해 보면,
1. 실시간 양방향 데이터 통신이 필요한 경우
2. 많은 수의 동시 접속자를 수용해야 하는 경우
3. 브라우저에서 TCP 기반의 통신으로 확장해야 하는 경우
4. 개발자에게 사용하기 쉬운 API가 필요할 경우
5. 클라우드 환경이나 웹을 넘어 SOA 로 확장해야 하는 경우

그리고 각 경우에 대한 설명이 자세히 나열되어 있으니 스스로 번역해서 음미 바란다
(누가 좀 안해주나 ^^;)


지원되는 브라우저 현황
IE와 오페라를 제외한 사파리,크롬,파이어폭스 최신버전에서 웹 소켓을 지원한다

 

 



그림1. 브라우저별 Web Sockeet 지원 현황 (출처: http://caniuse.com/)


웹 소켓 구현하기
웹 소켓 역시 일반적인 TCP 소켓 통신처럼 웹 소켓 역시 서버와 클라이언트간 데이터 교환이 이루어지는 형태이다. 따라서 다른 HTML5 스펙과는 달리 클라이언트 코드만으로 실행 가능한 예를 만들 수는 없다

즉 클라이언트에서는 웹 소켓이 제공하는 자바스크립트 API를 이용해 서버에 연결하고 데이터를 송/수신하는 코드를 구현해야 하며 서버에서는 웹 소켓 프로토콜에 맞는 전용 장치가 구축되어 있어야 한다

웹 소켓 클라이언트
웹 소켓이 제공하는 클라이언트 측 API는 매우 심플하다. 기본적인 서버 연결, 데이터 송신, 데이터 수신만 정의하면 나머지는 일반적인 스크립트 로직일 뿐이다

서버연결

웹 소켓이 동작하기 위해서 제일 처음 서버와 연결이 되어야 한다. HTML5가 제공하는 WebSocket 객체를 통해 서버 연결을 수행한다. 일반 통신은 ws, 보안 통신은 wss 프로토콜을 이용한다
기본 포트 역시 http,https와 동일한 80,443을 이용한다
var wSocket = new WebSocket("ws://yourdomain/demo");

데이터 송신
서버와 연결이 되면 이제부터 데이터를 주고 받을 수 있게 된다. WebSocket 객체의 send 함수로 데이터를 서버로 송신할 수 있다
wSocket.send("송신 메시지");

데이터 수신
서버에서 푸시(전송)하는 데이터를 받으려면 message 이벤트를 구현하면 된다
wSocket.onmessage function(e){ //매개변수 e를 통해 수신된 데이터를 조회할 수 있다 

클라이언트 API는 이 세가지가 핵심이다. 추가로 아래와 같은 이벤트도 제공된다
open 이벤트: 연결이 설정되면 발생
close 이벤트: 연결이 끊어지면 발생

웹 소켓을 이용하는 클라이언트 코드의 전체 모습은 대략 다음과 같다

<script>
  var wSocket = new WebSocket("ws:yourdomain/demo");
  
  wSocket.onmessage = function(e){  alert(e.data);  }  

  wSocket.onopen = function(e){ alert("서버 연결 완료"); } 
  wSocket.onclose = function(e){ alert("서버 연결 종료"); }  

  function send(){ //서버로 데이터를 전송하는 메서드
    wSocket.send("Hello");
  }
</script>

보는 바와 같이, 소켓 통신을 위한 클라이언트 측 코드는 매우 심플하며 직관적이다. 하지만 말했듯이 클라이언트 코드 만으로 데모는 실행되지 않는다. 클라이언트와 통신하는 서버가 존재해야 하는데 아래에 계속 이어진다

웹 소켓 서버
웹 소켓은 일반적인 TCP 소켓과는 다른 프로토콜로 설계되었다. 따라서 기존 TCP 서버를 그대로 이용할 수 없고 새로 구현해야 하는데 웹 소켓 서버 사양에 맞도록 구현해야 한다. 

웹 소켓 서버를 위한 다양한 오픈소스가 온라인에서 제공되고 있는데,
pywebsocket , phpwebsocketjWebSocketweb-socket-rubySocket.IO-node 와 같은 모듈을 이용하면 웹 소켓 서버를 쉽게 구축할 수 있다

이 글에서는 jWebSocket을 이용해서 웹 소켓 서버를 구축하고 제공되는 데모를 실행해 보도록 하자

jWebSocket 라이브러리는 http://jwebsocket.org/
 사이트를 통해 다운로드 받을 수 있는데
자바로 구현된 웹 소켓 서버모듈인 jWebSocketServer와 자바스크립트로 구현된 웹 소켓 클라이언트 데모인 jWebSocketClient 을 다운받으면 된다. 참고로 jWebSocket 라이브러리의 전체 소스코드는jWebSocketFullSource를 다운받아 볼 수 있다

jWebSocketServer 구동
우선 웹 소켓 서버를 구동 시켜야 하는데, 아파치 웹서버나 톰켓을 이용하여 구동하거나 Stand-Alone 으로도 구동시킬 수 있다. 이 글에서는 간단한 테스트를 위해 Stand-Alone로 구동시켜 보도록 하자

jWebSocketServer 가 자바로 구현되었기 때문에 자바 가상 머신이 설치되어 있어야 한다
서버에 최소 1.5 버전 이상의 자바런타임을 설치하도록 하자
그리고 기본적인 자바 환경 변수인 JAVA_HOME 과 java.exe를 Path에 등록한다

이제 자바를 위한 기본 설정이 마무리 되었으니 jWebSocketServer를 구동시키면 된다
Stand-Alone로 구동시키기 때문에 별도의 웹 서버는 필요하지 않고 배치파일을 실행하는 것으로 대신할 수 있다. 다운받는 jWebSocketServer을 압축해제 하고 bin 폴더에 있는 jWebSocketServer.bat 파일을 명령프롬프트에서 실행하도록 하자. 배치파일을 실행하면 설정을 위한 일련의 작업들이 진행되고 최종적으로 다음과 같은 모습으로 웹 소켓 서버의 구동이 시작된다



이후 웹 소켓 서버와의 통신로그와 디버그 메세지들이 이 창에 계속 기록된다
배치파일을 실행하는 동안 서버가 구동되는 것이기 때문에 실행창을 닫으면 서버도 종료됨을 기억하자

다음의 퀵스타트를 참고 하자
http://code.google.com/p/jwebsocket/wiki/QuickStart

jWebSocketClient 데모 테스트 하기
서버가 준비되었으니 웹 소켓 통신을 수행하는 클라이언트 데모를 확인해 보자
jWebSocketClient 를 다운받아서 압축해제 하면 다양한 데모가 미리 준비되어 있다
우리는 여기서 채팅데모인 chat.htm 을 실행해 보자

웹 소켓을 지원하는 브라우저를 두 개 띄우고 chat.html을 실행한다. 아래 그림은 크롬 브라우저의 실행 모습이다. 두 개의 브라우저에서 각각 로그인 한 뒤, 채팅하는 모습이다



채팅 외에도 다양한 데모가 있으니 참고 바라며 웹 소켓서버 통신의 기술적 구현을 배우기 위해 코드를 꼼꼼히 살펴보는 것도 좋을 것이다. 

참고로 jWebSocket 에서 서버 연결을 위해 다음과 같은 url을 정의하고 있다
var lURL = jws.JWS_SERVER_URL + "/;prot=json,timeout=360000";
...
JWS_SERVER_URL: "ws://" + ( self.location.hostname ? self.location.hostname : "localhost" ) + ":8787"

ws 프토토콜로 localhost8787포트로 연결하며 추가로 json 포맷과 타임아웃이 설정되었다

마지막으로 WebSocket 은 다른 HTML5 사양보다 프로그램적인 성격이 강하다. 
특히 클라이언트 코드만으로 해결될 수 있는 것이 아니라 좀 더 복잡해 보일 수 있다. 
또한 많은 수의 클라이언트를 수용하기 위해서는 소켓 서버의 성능과 가용성이 확보되어야 하기 때문에 보다 신중한 접근이 필요하다 하겠다. 글에서 소개한 웹 소켓 서버 라이브러리를 적절히 이용하거나 오픈 소스를 분석해서 내공을 키우기 바란다

참고>
Firefox의 웹소켓(WebSocket) 기능
http://code.google.com/p/websocket-sample/

http://dev.w3.org/html5/websockets/
http://www.websockets.org/about.html
http://www.codeproject.com/KB/webservices/c_sharp_web_socket_server.aspx

 

 

=================================

=================================

=================================

 

 

기타 참고 링크

http://www.slideshare.net/hiscale/111217

 

http://www.sqler.com/399721

 

 

=================================

=================================

=================================

 

 

반응형


관련글 더보기

댓글 영역