WebSocket is working well for ws://echo.websocket.org/ but not working on localhost
I have working example, where WebSocket works for ws://echo.websocket.org/
As follows,
<!DOCTYPE HTML>
<html lang = "en">
<head>
<title>WebSocket Test</title>
<meta charset = "UTF-8" />
<style type = "text/css">
h1 {
text-align: center;
}
.error {
color: red;
}
.response {
color: blue;
}
fieldset {
width: 80%;
margin: auto;
text-align: center;
-moz-box-shadow: 10px 10px 10px #000000;
-webkit-box-shadow: 10px 10px 10px #000000;
}
#output {
font-family: monospace;
width: 80%;
margin-left: auto;
margin-right: auto;
margin-top: 1em;
background-color: #eeeeee;
padding: 1em;
border: 5px groove #cccccc;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
-moz-box-shadow: 10px 10px 10px #000000;
-webkit-box-shadow: 10px 10px 10px #000000;
}
</style>
<script language="javascript" type="text/javascript">
var output;
var websocket;
function init(){
output = document.getElementById("output");
} // end init
function connect(){
//open socket
if ("WebSocket" in window){
websocket = new WebSocket("ws://echo.websocket.org/");
//note this server does nothing but echo what was passed
//use a more elaborate server for more interesting behavior
output.innerHTML = "connecting..." ;
//attach event handlers
websocket.onopen = onOpen;
websocket.onclose = onClose;
websocket.onmessage = onMessage;
websocket.onerror = onError;
} else {
alert("WebSockets not supported on your browser.");
} // end if
} // end connect
function onOpen(evt){
//called as soon as a connection is opened
output.innerHTML = "<p>CONNECTED TO SERVER</p>";
} // end onOpen
function onClose(evt){
//called when connection is severed
output.innerHTML += "<p>DISCONNECTED</p>";
} // end onClose;
function onMessage(evt){
//called on receipt of message
output.innerHTML += "<p class = 'response'>RESPONSE: "
+ evt.data + "</p>";
} // end onMessage
function onError(evt){
//called on error
output.innerHTML += "<p class = 'error'>ERROR: "
+ evt.data + "</p>";
} // end onError
function sendMessage(){
//get message from text field
txtMessage = document.getElementById("txtMessage");
message = txtMessage.value;
//pass message to server
websocket.send(message);
output.innerHTML += "<p>MESSAGE SENT: " + message + "</p>";
} // end sendMessage
</script>
</head>
<body onload = "init()">
<h1>Web Socket Echo Chamber</h1>
<form action = "">
<fieldset>
<button type = "button"
onclick = "connect()">
connect to server
</button>
<label for = "txtMessage">
<input type = "text"
id = "txtMessage"
value = "HTML5 Quick Reference For Dummies" />
</label>
<button type = "button"
onclick = "sendMessage()">
send message
</button>
<button type = "button"
onclick = "websocket.close()">
disconnect
</button>
</fieldset>
</form>
<div id="output">Click 'connect' button to connect</div>
</body>
</html>