Project

General

Profile

Wt as the server API » WebSocket.html

Example WebSocket Client - Georgiy Gluhoedov, 06/16/2016 09:14 PM

 
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id="btn-send">send data</button>
<button id="btn-close">close</button>

<button id="btn-send-get">send get</button>
<button id="btn-send-post">send post</button>

<script type="text/javascript">
var socket = null;

function createSocket() {
socket = new WebSocket('ws://127.0.0.1:5555/my-socket');

socket.onopen = function() {
console.log('socket connected')
};

socket.onclose = function(event) {
console.log('socket closed');
};

socket.onmessage = function(event) {
console.log('socket message:', event.data);
};

socket.onerror = function(error) {
console.error('socket error:', error);
};
}

function sendRequest(url, data, method) {
var request = new XMLHttpRequest();

request.open(method, url, true);

request.onload = function (e) {
console.log(this.responseText);
};

request.onerror = function (e) {
console.error('error request');
};

request.send(data);
}

createSocket();

document.querySelector('#btn-send').addEventListener('click', function () {
if (socket.readyState === 3) {
console.warn('сокет уже закрыт');
return;
}

socket.send('custom data');
});

document.querySelector('#btn-close').addEventListener('click', function () {
socket.close();
});

document.querySelector('#btn-send-get').addEventListener('click', function () {
sendRequest('http://127.0.0.1:5550/foo', 'data', 'GET');
});

document.querySelector('#btn-send-post').addEventListener('click', function () {
sendRequest('http://127.0.0.1:5550/bar', 'data', 'POST');
});

</script>
</body>
</html>
    (1-1/1)