Sending a message to the browser

The channel is open, but there is not communication going on. Time to send some messages to the browser from TouchDesigner.
For this to have any effect, we need to define the onmessage of our websocket element. As with the websocket_open function, lets create a websocket_receive function with an event as an argument.
In this case, the event holds some important information for us, kinda like the request dictionary from the http request. By accessing the data member of the event, we can get the content of the message, and just print it out.

function websocket_receive(event){
	console.log(event.data);
}

In our websocket_init function,. we set onmessage member of our websocket to the newly created function.

ws.onmessage = websocket_receive;

Lets head back to TouchDesigner. to actually send something.
Its good that we still have our table of clients, so we can use this, because for the webSocketSendText function of the webserver to work we need a client to address the messageto.
Create a new textDAT and use the following code

data = "This is the message we send"
client = op('table1')[1, 0].val
op('webserver1').webSocketSendText(client, data) 

No, rightclick on the textDAT and use “Run Script” or press CTRL + R. Check the console of the browser, it should now display “This is the message we send”.

<html>
	<head>
		<script>
			var ws;
			function websocket_open(event){
				console.log('Websocket open')
			}
			
			function websocket_receive(event){
				console.log(event.data);
			}

			function websocket_init(){
				ws = new WebSocket('ws://localhost:9980');
				ws.onopen = websocket_open;
				ws.onmessage = websocket_receive;
			}
		</script>
	</head>
	<body onload = "websocket_init()">
		<img src = "noise1" > </br>
		<p>This is a TouchDesigner website</p>
	</body>
</html>