Interact with Kaazing WebSocket Gateway Using the WebSocket API
This procedure describes how you can use the WebSocket API, provided by the Kaazing Flash client library, in ActionScript. This API allows you to take advantage of the WebSocket standard as described in the HTML5 specification. You can create a Flash application that uses the Kaazing Flash client library to interact directly with a back-end server. The support for WebSocket is provided by the WebSocket class and its supporting classes.
The following steps show you how to use the WebSocket API in an existing Flash application. This example highlights some of the most commonly used WebSocket methods and is not meant to be an end-to-end tutorial. Refer to the ActionScript WebSocket API documentation for a complete description of all the available methods.
Before You Begin
This procedure is part of Checklist: Build Flash Clients Using Kaazing WebSocket Gateway:
- Set Up Your Development Environment
- Interact with Kaazing WebSocket Gateway Using the WebSocket API
- Interact with Kaazing WebSocket Gateway Using the EventSource API
- Secure Your Flash Client
- Display Logs for the Flash Client
- Troubleshoot Your Flash Client
Note: Learn about supported browsers, operating systems, and platform versions in the Release Notes.
To Use the WebSocket API
- Add the necessary import statements:
import com.kaazing.gateway.client.html5.MessageEvent import com.kaazing.gateway.client.html5.WebSocket
- Create a new WebSocket object:
var webSocket:WebSocket = new WebSocket(url)
- Add event-handlers to the WebSocket object to listen for WebSocket events, as shown in the following example. The WebSocket object has three methods: the onopen method is called when a WebSocket connection is established, the onmessage method is called when messages are received, and the onclose method is called when the WebSocket connection is closed.
webSocket.onopen = openHandler webSocket.onmessage = readHandler webSocket.onclose = closeHandler
- Define the three functions on the WebSocket object:
private function openHandler(ev:Event):void { trace("CONNECTED\n"); } private function readHandler(ev:Event):void { var msg:String = ev.data trace("MESSAGE: "+msg+"\n"); } private function closeHandler(ev:Event):void { trace("CLOSED\n"); }
After the eventHandlers are set, the WebSocket constructor causes the WebSocket to connect to the back-end server. - While the WebSocket connection is open (that is, after the onopen event-handler is called and before the onclose event-handler is called), you can use the send method to send text-only messages, as shown in the following example.
webSocket.send("Hello World!")
Next Step
Interact with Kaazing WebSocket Gateway Using the EventSource API
Notes
- To view sample source code using the WebSocket API, see the ws.mxml file located in GATEWAY_HOME/demo/flash/src/gateway.