Flash Socket Programming What is a Socket? A Socket is a mechanism used to send data over a network (e.g. the Internet), it is the combination of an IP address and a port. The IP address is used to specify the computer (on the network) to connect to and the port (which is not a physical port just a software construct represented by a number) specifies which port on the computer to connect to. There are multiple ports to allow multiple distinct connections to a single IP address, certain ports traditionally have certain uses for example HTTP servers use 80 and POP3 servers use 110. Restrictions and Security ActionScript has many restrictions that (to be brutally honest) cripple, but not entirely, the usefulness of Sockets. Firstly, there are security issues, for a Flash application to connect to a particular server that server must host a policy file defining what ports Flash is allowed to connect to. This restricts Flash from connecting to most of the servers on the Internet although it isn’t too much trouble to put a policy file on your server. Secondly, Flash isn’t allowed to create server sockets (sockets that clients can connect to) either, so to make a multiplayer game would require that the game is hosted on a server which all of the clients connect to. The server would have to constantly send data to all of the clients; this could potentially use a lot of bandwidth. Finally, only one type of transportation protocol is supported that is TCP. Although TCP is very good for sending data like webpages and such it is not so good at sending real-time data. This means that multiplayer real-time games are slower than they could be or infeasible. Never mind all that though, Flash Sockets are still useful. Creating a Socket Creating a socket is fantastically straight forward, since there are no decisions to make about the type of Socket. Here is an example with all of the event listeners added:
import flash.net.Socket;
import flash.events.*;

var socket:Socket = new Socket();

Security.allowDomain("*");

socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(Event.CLOSE, onClose);
socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecError);

socket.connect("hejp.co.uk", 80);
It is wise to connect after adding the event listeners because an event could be dispatched without any code to respond to it, or something strange like that. This example connects to hejp.co.uk using port 80 i.e. my web server. Quick description of the Events:
  • CONNECT: dispatched when the connection is established
  • CLOSE: dispatched when the connection is closed
  • IO_ERROR: dispatched when an error occurs
  • SOCKET_DATA: dispatched when socket can be read
  • SECURITY_ERROR: dispatched when security gets in the way
Using the Socket Using the socket involves implementing the listener functions. In this example we’ll make a request for the index page of hejp.co.uk and trace the response. Doing so involves writing a HTTP request to the port and then reading the response.
function onConnect(e:Event):void {
	socket.writeUTFBytes("GET / HTTP/1.1\n");
	socket.writeUTFBytes("Host: hejp.co.uk\n");
	socket.writeUTFBytes("\n");
}

function onClose(e:Event):void {
	// Security error is thrown if this line is excluded
	socket.close();
}

function onError(e:IOErrorEvent):void {
	trace("IO Error: "+e);
}

function onSecError(e:SecurityErrorEvent):void {
	trace("Security Error: "+e);
}

function onResponse(e:ProgressEvent):void {
	if (socket.bytesAvailable>0) {
		trace(socket.readUTFBytes(socket.bytesAvailable));
	}
}
Notes A Flash app running the Flash IDE runs in a completely different security sandbox to a Flash app running in the browser, therefore even though an works running in the IDE errors (usually security errors) can crop up while running in the browser.

23 Responses to “ActionScript 3: Socket Programming”

  1. Rachit Jain Says:

    Hi,
    I am making a multi-user flash application, and I am desperately in need of some help. I want to use socket programming, so that two people can work in real-time.
    I want to transfer the mouse cordinates from one user to the other connected user, and from the other to the 1st.
    what should i do??
    please help.

    thanks

    p.s. I found the information very helpful.

    [Reply]

    hejp Reply:

    Hello Rachit,

    I’m afraid this can’t be done purely in Flash because of security issues the Flash Player can’t open a ServerSocket, which is necessary for the two computers to connect directly.

    If you really need to use AS3 you can write a Adobe AIR desktop application, otherwise you could use Java for example which has very good libraries for network communication and GUI creation.

    Alternatively you could write a PHP script (on a remote server) or Java application (remote or local) to act as a proxy, relaying the mouse co-ords.

    Hope this made sense.

    [Reply]

  2. kevin Says:

    can you help us with our project? socket programming in flash-created game. we know nothing about socket programming…even in adobe flash. but we already have our game at the moment..our problem now is with regards to socket programming.

    regards,
    kevin

    [Reply]

  3. wajdi Says:

    thanks for this great tut, i have a problem in my socket connection i don’t know why it desconnect after sending a message by calling writeUTFBytes() i create a php socket script, the console displays my message and in my swf the data is recived, but after i recive dta it disconnect directly please help me am working on important project

    thanks again :)

    [Reply]

    hejp Reply:

    Hi Wajdi,

    It’s tricky to tell since any one of many causes could be to blame.

    Try and add an event listener to listen for EOFError events, and see if an exception is being caught and closing the socket.

    Are you sure the php socket isn’t closing? Maybe you can use telnet to test the php.

    [Reply]

  4. Errol Rizzardo Says:

    How to load a different HTML document in another directory?

    [Reply]

  5. vassa Says:

    Hi, thanks for for sharing that great post. I have a problem with the close socket event. When I disconnect my wifi, the event is not dispatched. Any clue?

    [Reply]

  6. burek Says:

    Just to say thanks for this great article :) It helped me a lot :)

    [Reply]

  7. Chipmunk Says:

    Hi,

    I am getting this error

    IO Error: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2031: Socket Error. URL: 127.0.0.1"]

    [Reply]

  8. José Martins Says:

    Very useful post, thank you! With that I’m trying to do this: http://stackoverflow.com/questions/13746553/send-file-from-c-sharp-server-to-as3-flash-clients

    If by any chance you could give some input it would be great!

    [Reply]

  9. wildwood hotels Says:

    They really need to go into a discussion of how to prevent your info
    from being ‘accessible’ to others and the implications,’ Robles said, ‘But of course, this would prevent Facebook from growing their revenue.
    But when people click on your search listing, they wont be able to see all of
    the information in your profile (timeline).
    Include letters, symbols and digits in your password to increase its strength.

    [Reply]

  10. green coffee beans review Says:

    He is with the University of California, Davis studies the health effects
    of the antioxidants in green coffee bean & dr. oz extract helps promote weight loss.
    As it is made up of natural ingredients, there are lots of people interested in a lot easier
    ways where they can shed pounds. Sugar turns to fat, and help you get appearing and also feeling better in
    no time at all she had lost 25 pounds. And most importantly, it has been obtained.

    [Reply]

  11. private proxy Says:

    Good writing. I liked that writing.

    [Reply]

  12. world of warcraft items Says:

    Good web site you have got here.. It’s hard to find quality writing like
    yours nowadays. I honestly appreciate people like you!
    Take care!!

    [Reply]

  13. Alek Says:

    What about bandwidth usage in case of web sockets in HTML5?

    [Reply]

  14. personal injury lawyer washington Says:

    I need to to thank you for this good read!! I definitely loved every bit of it.
    I’ve got you saved as a favorite to check out new things you
    post…

    [Reply]

  15. make face Says:

    This blog was… how do you say it? Relevant!! Finally I’ve found something
    that helped me. Many thanks!

    [Reply]

  16. how to become an alpha male Says:

    I reside in Dallas. Despite the fact that you’ll find practically twenty,000 a lot more males within
    this town than girls, this figure is really a little bit deceptive.

    There’s a higher quantity of gay males, and also immigrant workers,
    who skew the figures. All the places on the list seem to become massive metropolitan areas
    that possibly have equivalent forms of populations.

    If you are just searching to get a wonderful place to
    party then it really is excellent. If you are looking for a boyfriend or spouse, you’ll be disappointed.

    My website how to become an alpha male

    [Reply]

  17. http://www.youtube.com/ Says:

    Though there is usually nothing to worry about, the feelings seem quite real
    and terrifying in the moment. Up coming,permit specific that the internal do yoou
    encounter feeling is the fact sufficiently maintained.
    Your anxiety disorder is actually a diagnosable and treatable disorder, an illness as real as
    diabetes.

    [Reply]

  18. Dipak Panchasara Says:

    I have try this code but its give me a below Error :

    Help me to solve this

    Thanks Kind Regards

    Security Error: [SecurityErrorEvent type="securityError" bubbles=false cancelable=false eventPhase=2 text="Error #2048: Security sandbox violation: file:///C|/Users/Admin/Documents/test%20FLA/testSocket.swf cannot load data from 192.168.0.180:4010."]

    [Reply]

  19. Robt Says:

    Hey very nice blog!

    Also visit my webpage … accurate time (Robt)

    [Reply]

  20. Mckinley Says:

    Hello there, I do think your site may be having web browser compatibility issues.
    When I look at your blog in Safari, it looks fine however, when opening in IE,
    it’s got some overlapping issues. I merely wanted to provide you with a quick heads up!

    Besides that, fantastic website!

    Also visit my web-site juicer recipes mint (Mckinley)

    [Reply]

  21. apple unlocked iphone 5 Says:

    Now I am going away to do my breakfast, when having my
    breakfast coming yet again to read further news.

    Have a look at my weblog; apple unlocked iphone 5

    [Reply]

Leave a Reply