I have simple project about connect between java server and javascript client via websocket. Here my HTML file:
<body>
<h3>Demo WebSocket</h3>
<script type="text/javascript">
var arr;
var websocket;
connect();
function connect() {
websocket = new WebSocket('ws://127.0.0.1:4444');
websocket.onopen = function () {
var i = (typeof websocket != 'undefined'&& websocket.readyState == WebSocket.OPEN);
textAreaMessage.value += "Server ..." + i + "\n";
};
websocket.onmessage = function (message) { processMessage(message); };
websocket.onclose = function (message) { processClose(message); };
websocket.onerror = function (message) { processError(message); };
}
function disconnect() {
websocket.close();
}
function processOpen(message) {
}
function processMessage(message) {
console.log(message);
arr = JSON.parse(message.data)
textAreaMessage.value += "Response From Server ==> " + arr[0] + " \n";
}
function processClose(message) {
textAreaMessage.value += "Server Disconnect... \n";
}
function processError(message) {
textAreaMessage.value += "Error... " + message + " \n";
}
function sendMessage() {
if (typeof websocket != 'undefined'&& websocket.readyState == WebSocket.OPEN) {
websocket.send(textMessage.value);
textAreaMessage.value += "Send to Server ==> " + textMessage.value + " \n";
textMessage.value = "";
}
}
</script>
</body>
when server send String via websocket to client, value of massage will store in mesage.data
but i converted it to JavaScript object use arr = JSON.parse(message.data)
And then i conole.log(arr)
and i see:
and I get each element of arr via index like: arr[index]
.
The important thing is when the new value come via websocket then the value of element also change. I want display the value of element in page and its displayed value automatically changes when its value is changed.
Somebody can help me?
Sorry about my grammar.
Thank you so much!