O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Connecting to a Socket Server

Problem

You want to establish a connection with a socket server.

Solution

Use either the Socket.connect() or XMLSocket.connect() method and listen for the connect event to be notified when a connection is made.

Discussion

To connect to a socket server, there are two critical pieces of information that you need to know before attempting to make a connection. The first is the domain name or IP address of the server to which the connection will be made, and the second is the port over which the connection should take place.

Whether you are using a Socket or an XMLSocket instance, the connection process is exactly the same; both classes define a connect() method that takes two parameters:

host

A string value specifying the host to connect to, either with a domain name such as www.example.com, or with an IP address such as 192.168.1.101. To connect to the web server the Flash movie is being served from, pass null instead of a string hostname.

port

An int value specifying the port number that should be used to connect to the host. The port value must be at least 1024, unless the server has a policy file specifically allowing ports less than 1024.

Because of the asynchronous nature of socket programming in Flash, the connect() method does not wait for a connection to happen before continuing to the next line of ActionScript code. If you try to interact with a socket before a connection has been fully established, you’ll encounter unexpected results and your code ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required