Last active
August 7, 2019 18:18
-
-
Save pegasuspect/c1303a6c5f8f25d4b8e25b8099b50d40 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
// This is the JavaScript file for the basic LabVIEW WebSockets demo. | |
// Copyright © 2016 by MediaMongrels Ltd. | |
class Connect { | |
constructor(port, ind) { | |
this.ind = ind.toString(); | |
this.num = port; | |
this.sendString = '#port' + this.ind + 'send'; | |
this.chatString = '#port' + this.ind + 'chat'; | |
this.host = "ws://localhost:" + this.num; | |
this.socket = new WebSocket(this.host); | |
this.attachHandlers(); | |
this.sendMessage(); | |
} | |
sendMessage(){ | |
try | |
{ | |
this.message('<p class="event">Socket Status: ' + this.socket.readyState + ' (create)', this.chatString); | |
// Tell the user the connection has been established | |
this.socket.onopen = function(){ | |
this.message('<p class="event">Socket Status: ' + connect.socket.readyState + ' (open)', this.chatString); | |
}.bind(this) | |
// Display the received message | |
this.socket.onmessage = function(msg){ | |
this.message('<p class="message">Received: ' + msg.data, this.chatString); | |
}.bind(this) | |
// Tell the user the connection has been closed | |
this.socket.onclose = function(){ | |
this.message('<p class="event">Socket Status: ' + connect.socket.readyState + ' (Closed)', this.chatString); | |
}.bind(this) | |
} | |
catch(exception){ | |
this.message('<p>Error' + exception, this.chatString); | |
} | |
} | |
attachHandlers(){ | |
$(this.sendString).keypress(function(event) { | |
if (event.keyCode == '13') { | |
this.send(this.sendString); | |
} | |
}); | |
// Close the connection from the client side | |
$('#port' + this.num + 'disconnect').click(function(){ | |
this.socket.close(); | |
}); | |
$('#error').text('port ' + this.ind + ' processed...'); | |
} | |
message(msg, ctrl){ | |
$(ctrl).append(msg + ' :' + this.ind + '</p>'); | |
} | |
send(ctrl){ | |
var text = $(ctrl).text(); | |
$(ctrl).text(""); | |
if(text == ""){ | |
this.message('<p class="warning">Please enter a message'); | |
return; | |
} | |
try { | |
connect.socket.send(text); | |
this.message('<p class="event">Sent: '+text,ctrl.slice(0,6)+'chat') | |
} catch(exception){ | |
this.message('<p class="warning">'); | |
} | |
} | |
} | |
var port = 3000 | |
var firstConnection = new Connect(port, 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment