AS3 – TCP chat with buffering and acknowledgment

There are many classes in ActionScript 3.0 to use sockets, like as Socket, ServerSocket, XmlSocket (in package) for TCP connections, NetGroup for UDP connections or NetStream and NetConnection to use Flash Media Server products.As I have liked Socket Programming in native programming languages from the past, I decided to create a simple TCP chat using socket facilities in AS3.
I used Socket and ServerSocket of package and wrote a simple Client/Server TCP chat (Server side must be implemented in AIR).After many tests, I faced with a serious problem in READ functions of AS3 sockets. Sometimes when you send messages concurrently (ex: in a loop), data not received correctly in other side.

At first, I thought that may some packet lost occurred. But, considering the all possible cases, showed me that this happened due to buffering problems of AS3 event handling system.

If you use a dangerous routine (duo to freezing the application) like this to receive data with same size as sent from other side, you can receive all data without any bits less or more.

while (socket.dataAvailable) {
buffer += socket.readData
However if you want to use a regular mechanisms like reading available data by ProgressEvent.SOCKET_DATA event triggeration, in some cases you will not receive all things.The truth is that sometimes data is available but not any event triggers, so when the event will trigger, there may be not enough data to receive.What is the solution?

Solution is in Adobe hands, I don’t know, but I decided to set an acknowledgement system in my application. Therefore, I wrote four classes as below:

  • A class to define a packet (ASCII messages, but you can add ByteArray or other objects if you need), size of them, signatures and …
  • Customized socket event.
  • Wrapper class of clients, with buffering mechanism for any sending messages and timer and acknowledgement routines. Any sending message will store in a buffer (queue) and will send after receiving ACK of previous messages.
  • Wrapper class of server that uses a list for handling multi clients.

I hope that, there is enough time for me to completing this project, but if you interested in use or enhance these classes, get them from

About محمد شمس

برنامه‌نویس، طراح انیمیشن و علاقمند به هوش مصنوعی

پاسخ دهید