Sponsored By

AS3 sockets with C++

This short tutorial shows some sample code to get started with networking C++ and AS3. This tutorial expects that you have a basic understanding of C++, AS3, and network programming. Also this is my first tutorial.

Luke Manrodt, Blogger

January 14, 2012

4 Min Read
Game Developer logo in a gray background | Game Developer

A brief description of my development environment:

    Visual C++ Express 2008

    Flash Develop 4.0 (I highly reccomend this as a free Flash project IDE.)

    Windows 7 x64

    Apache 2.2 web server

 

Since I have my web server on my development machine all my host connections are to "localhost"

 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

AS3 code:

package
{
    import flash.display.Sprite;
    import flash.net.Socket;
    import flash.text.TextField;
    import flash.events.*;

    /**
     * ...
     * @author Luke Manrodt
     */
    public class Main extends Sprite
    {
        private var testText:TextField; //used to show us our connection status
        private var sock:Socket;
        private var host:String = "localhost";
        private var port:int = 8004;
       
        public function Main():void
        {
            testText = new TextField();
            testText.text = "main";
            testText.x = 150;
            testText.y = 150;
            testText.width = 600;
            stage.addChild(testText);
           
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }

        private function init(e:Event = null):void
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            // entry point
           
            sock = new Socket();

            sock.addEventListener(Event.CONNECT, OnConnect);
            sock.addEventListener(Event.CLOSE, OnClose);
            sock.addEventListener(IOErrorEvent.IO_ERROR, OnError);
            sock.addEventListener(ProgressEvent.SOCKET_DATA, OnResponse);
            sock.addEventListener(SecurityErrorEvent.SECURITY_ERROR, OnSecError);
           
            sock.connect(host, port);       
           
            testText.text = "connecting to "+host;
        }
       
        public function OnConnect(e:Event = null):void
        {
            testText.text = "connected to "+host;
        }
       
        public function OnClose(e:Event = null):void
        {
            testText.text = "connection closed";
            sock.connect(host, port);   
        }
       
        public function OnError(e:Event = null):void
        {
            testText.text = "IO error";
        }
       
        public function OnResponse(e:Event = null):void
        {
            testText.text = "data recieved";
        }
       
        public function OnSecError(e:Event = null):void
        {
            testText.text = "security error";
        }
    }
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

C++ code:

#include <winsock2.h> //socket
#include <iostream> //std
#include <string> // string
#include <windows.h>

#pragma comment (lib, "ws2_32.lib")
using namespace std;

int main(int argc, char** argv)
{   
  SOCKET serverSock;
    sockaddr_in serverAddr;
    hostent* localhost;
  WSADATA wsData;
  string port = "8004";

  //initialize winsock
  int result = WSAStartup(MAKEWORD(2,2), &wsData);
  if(result)
  {
    cout<<"Error starting winsock. EC:"<<result;
    return 1;
  }

  //CreateSocket
  serverSock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0);
    if(serverSock == INVALID_SOCKET)
    {
        cout<<"socket() Error"<<endl;
       
    system("pause");
    exit(1);
    }

    localhost = gethostbyname("");
   
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serverAddr.sin_port = htons(atoi(port.c_str()));

  unsigned long mode = 1;
  ioctlsocket(serverSock, FIONBIO, &mode);

    if(bind(serverSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR)
    {
        cout<<"Binding of Socket failed EC:"<<WSAGetLastError()<<endl;
       
      system("pause");
      exit(1);
    }


  int ret;

  sockaddr_in inAddr;
    SOCKET clientSock;
  int namelen = sizeof(sockaddr_in);
  SecureZeroMemory(&inAddr, namelen);

  bool listening = true;
    while(listening)
    {
        result = listen(serverSock, 10);
        if(result == SOCKET_ERROR)
        {
            cout<<"Unable to listen on socket"<<endl;
            return WSAGetLastError();
        }

    bool hasConnection = false;
    while(!hasConnection)
    {
          clientSock = accept(serverSock, (sockaddr*)&inAddr, &namelen);
          if(clientSock == INVALID_SOCKET)
          {
        ret = WSAGetLastError();
        if(ret != WSAEWOULDBLOCK)
        {
          cout<<"unable to accept connection from "<<inet_ntoa(inAddr.sin_addr)<<" EC:"<<WSAGetLastError()<<endl;
             
          system("pause");
          exit(1);
        }
          }
      else
      {
        hasConnection = true;
      }
    }
   
    cout << "Connection established to "<<inet_ntoa(inAddr.sin_addr)<<endl;
    char inBuff[250];
    while(hasConnection)
    {
      ret = recv(clientSock, inBuff, 250, 0);
      if(ret == SOCKET_ERROR)
      {
        ret = WSAGetLastError();
        if(ret != WSAEWOULDBLOCK)
        {
          cout<<"Error recving from "<<inet_ntoa(inAddr.sin_addr)<<" EC:"<<ret<<endl;
          system("pause");
          exit(1);
        }
        ret = 0;
      }

      string recvStr;
      if(ret > 0)
      {
        recvStr.assign(inBuff, ret);
        cout<<recvStr<<endl;
      }

      ret = recvStr.find("<policy-file-request/>");
      if(ret != recvStr.npos)
      {
        //This is absolutley required for AS3 to allow the connection to go through.
        string outStr = "<?xml version=\"1.0\"?>\n";
               outStr.append("<cross-domain-policy>\n");
               outStr.append("<allow-access-from domain=\"*\" to-ports=\"*\"/>\n");
               outStr.append("</cross-domain-policy>");
        ret = send(clientSock, outStr.c_str(), outStr.length()+1, 0);
      }
    }

  }

  return 0;
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Read more about:

Blogs
Daily news, dev blogs, and stories from Game Developer straight to your inbox

You May Also Like