Last active
June 17, 2017 12:41
-
-
Save drwasho/9f2e64390e0ae372c554b9713c65c7ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function blue() { | |
// Get references to elements on the page. | |
var form = document.getElementById('message-form'); | |
var messageField = document.getElementById('message'); | |
var messagesList = document.getElementById('messages'); | |
var socketStatus = document.getElementById('status'); | |
var closeBtn = document.getElementById('close'); | |
// Create a new WebSocket. | |
var socket = new WebSocket('wss://echo.websocket.org'); | |
// Handle any errors that occur. | |
socket.onerror = function(error) { | |
console.log('WebSocket Error: ' + error); | |
}; | |
// Show a connected message when the WebSocket is opened. | |
socket.onopen = function(event) { | |
socketStatus.innerHTML = 'Connected to: ws://echo.websocket.org'; | |
socketStatus.className = 'open'; | |
}; | |
// Handle messages sent by the server. | |
socket.onmessage = function(event) { | |
var message = event.data; | |
messagesList.innerHTML += '<li class="received"><span>Received:</span>' + | |
message + '</li>'; | |
}; | |
// Show a disconnected message when the WebSocket is closed. | |
socket.onclose = function(event) { | |
socketStatus.innerHTML = 'Disconnected from WebSocket.'; | |
socketStatus.className = 'closed'; | |
}; | |
// Send a message when the form is submitted. | |
form.onsubmit = function(e) { | |
e.preventDefault(); | |
// Retrieve the message from the textarea. | |
var message = messageField.value; | |
// Send the message through the WebSocket. | |
socket.send(message); | |
// Add the message to the messages list. | |
messagesList.innerHTML += '<li class="sent"><span>Sent:</span>' + message + | |
'</li>'; | |
// Clear out the message field. | |
messageField.value = ''; | |
return false; | |
}; | |
// Close the WebSocket connection when the close button is clicked. | |
closeBtn.onclick = function(e) { | |
e.preventDefault(); | |
// Close the WebSocket. | |
socket.close(); | |
return false; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment