157. !DOCTYPE html
html
head
titleWebSocket Sample/title
script src=//ajax.googleapis.com/ajax/libs/jquery/2.0.2/
jquery.min.js/script
/head
body
div id=output style=width: 400px; height: 300px; border: 1px solid
#000; overflow: auto;
/div
div
input type=button id=connect value=connect /
input type=button id=close value=close /
input type=button id=values value=values /
/div
div
input type=text size=40 id=message value=메시지를 입력해주세
요. /
input type=button id=send value=send /
/div
/body
/html
158. var seq = 0;
var getSequence = function () {
return seq++;
}
var ws = null;
function initWebSocket() {
// WebSocket이 연결됐을 때 호출된다.
ws.onopen = function () {
$('div').html('[' + getSequence() + '] open').appendTo('#output');
};
// WebSocket이 닫혔을 때 호출된다.
ws.onclose = function () {
$('div').html('[' + getSequence() + '] close').appendTo('#output');
};
// WebSocket 연결에서 에러가 발생했을 때 호출된다.
ws.onerror = function () {
$('div').html('[' + getSequence() + '] error').appendTo('#output');
};
// 메시지를 수신하면 호출된다.
ws.onmessage = function (event) {
$('div').html('[' + getSequence() + '] message: ' +
event.data).appendTo('#output');
};
}
159. $('#connect').on('click', function (e){
// connect 버튼을 클릭하면 WebSocket을 통해 서버와 연결한다.
ws = new WebSocket('ws://localhost:8080', 'echo-protocol');
// WebSocket의 이벤트 핸들러를 등록한다.
initWebSocket();
});
// WebSocket의 연결을 종료한다.
$('#close').on('click', function (e){
ws.close();
});
// 여러 변 값을 출력한다.
$('#values').on('click', function (e){
var readystate = 아직 WebSocket이 생성되지 않았습니다.;
if(ws){
readystate = ws.readyState;
}
$('div').html('[' + getSequence() + '] readyState: ' +
readystate).appendTo('#output');
});
// text 상자의 내용을 읽어 서버로 전송한다.
$('#send').on('click', function (e){
var message = $('#message').val();
$('div').html('[' + getSequence() + '] ' + message).appendTo('#output');
ws.send(message);
});
160. GET ws://192.168.1.147:8080/ HTTP/1.1
Pragma: no-cache
Origin: http://localhost:8080
Host: 192.168.1.147:8080
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/
537.36
Cache-Control: no-cache
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Extensions: x-webkit-deflate-frame
Sec-WebSocket-Key: /+ogz/Ujwnew+Mcc1UnOww==
Sec-WebSocket-Protocol: echo-protocol
Sec-WebSocket-Version: 13
REQUEST
지원 가능한 extension
지원 가능한 protocol
handshake가 이루어졌음을
알려주기 위한 키
접속할 host 정보
연결을 시도한 host 정보