AS3 Socket/Server MMO Communication - c#

I'm working on a flash MMO with a c# server. I have a simple messaging protocol for the sockets. When a client joins he sends out this:
"%|clientId|need"
And positions are updated like this:
"$|clientId|xPosition|yPosition"
For some reason this isn't working. I store all the avatars in an array, the avatar class simply extends movieclip. This should add all clients into the room but it isn't working. Any ideas?
Edit: The error is probably in the client-side code above, I think it's with how I store the Avatars in an array.
Here is my code:
id.text = String(Math.random());
import flash.net.Socket;
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.utils.Dictionary;
var avatars:Array = new Array();
var _socket:Socket = new Socket();
_socket.addEventListener(ProgressEvent.SOCKET_DATA,socketData);
_socket.addEventListener(Event.CONNECT,socketConnected);
_socket.addEventListener(IOErrorEvent.IO_ERROR,socketError);
_socket.connect("192.168.1.4",8000);
function sendText(msg:String):void {
if (_socket.connected) {
_socket.writeUTFBytes(msg);
_socket.flush();
} else {
}
}
function socketConnected(e:Event):void {
chat.appendText("Connected. \n");
sendText("%|" + id.text + "|need");
//chat.scrollV = chat.maxScrollV;
}
function socketError(e:IOErrorEvent):void {
chat.appendText("SYSTEM MSG:"+e.text+"\n");
//chat.scrollV = chat.maxScrollV;
}
function socketData(e:ProgressEvent):void {
var str:String = e.currentTarget.readUTFBytes(e.currentTarget.bytesAvailable);
trace(str);
//var xml:XML = new XML(str);
chat.appendText(str + "\n");
//[pos]|50|334
if(str.search("$")){
var positionArray = str.split("|");
avatars[str[1]].x = str[2];
avatars[str[1]].x = str[3];
}
if(str.search("%")){
var miniArray = str.split("|");
avatars[miniArray[1]] = new Avatar();
addChild(avatars[miniArray[1]]);
dump.text = miniArray[1];
}
}
me.addEventListener(MouseEvent.MOUSE_DOWN, drag);
me.addEventListener(MouseEvent.MOUSE_UP, sDrag);
var timing:Boolean = false;
var t:Timer = new Timer(1);
t.addEventListener(TimerEvent.TIMER, tick);
function tick(e:TimerEvent){
if(timing){
sendText('$|'+id.text+'|'+me.x+'|'+me.y);
}
else{
}
}
t.start();
function drag(e:MouseEvent){
me.startDrag();
timing = true;
}
function sDrag(e:MouseEvent){
me.stopDrag();
timing = false;
}

Edit: Changing answer based on additional information.
You had a few problems after addressing the code. First was your use of if(str.search)... The $ and % can be parsed as a regular expression. Additionally since your chars were at an index of 0 these if's could fail to be true. Lastly your were using str[1] instead of positionArray[1] etc. Below is the working code with some hacking to test without the use of a socket server. Might show you some tricks on how to do some focused testing when you run into issues like this.
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
public class TestSocket extends Sprite
{
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.net.Socket;
import flash.utils.Dictionary;
import flash.utils.Timer;
[Embed(source="assets/avatar.png")]
private var Avatar:Class;
private var avatars:Array = new Array();
function TestSocket():void
{
socketSimulator(10);
}
function socketData(e:ProgressEvent):void {
var str:String = e.currentTarget.readUTFBytes(e.currentTarget.bytesAvailable);
trace(str);
if(str.indexOf("$") >= 0){
var positionArray = str.split("|");
avatars[positionArray[1]].x = positionArray[2];
avatars[positionArray[1]].x = positionArray[3];
}
if(str.indexOf("%") >= 0){
var miniArray = str.split("|");
avatars[miniArray[1]] = new Avatar();
addChild(avatars[miniArray[1]]);
}
}
/** Test Code **/
private var _numClients;
private function socketSimulator(numClients:int):void
{
_numClients = numClients;
var msg:String;
while(--numClients >= 0)
{
msg = "%|" + numClients + "|need";
sendFakeData(msg);
}
var timer:Timer = new Timer(500, 9999);
timer.addEventListener(TimerEvent.TIMER, sendFakeMovement);
timer.start();
}
private function sendFakeMovement(e:TimerEvent):void
{
var id:uint = Math.random() * _numClients;
var x:Number = Math.random() * 1000;
var y:Number = Math.random() * 1000;
var msg:String = "$|"+id+"|"+x+"|"+y;
sendFakeData(msg);
}
//This is just hacked test code, don't do this in production
private function sendFakeData(msg:String):void
{
var e:MyProgressEvent = new MyProgressEvent(ProgressEvent.SOCKET_DATA);
e.currentTarget = {
readUTFBytes: function(bytes:int = 0):String
{
return msg;
}
}
socketData(e);
}
}
}
import flash.events.ProgressEvent;
class MyProgressEvent extends ProgressEvent
{
private var _currentTarget:Object;
public function set currentTarget(val:Object):void
{
_currentTarget = val;
}
override public function get currentTarget():Object
{
return _currentTarget;
}
function MyProgressEvent(type:String):void
{
super(type);
}
}

Before you test log in/log off/position, make sure that your architecture supports sending and receiving data in the first place, I mean, send a string ("some data") on the front-end and check if you're really receiving ("some data") on the back-end. I am afraid the byte endianness that you're sending on the client is different from that on the server and so the server will mis-understand the incoming data. If so you need to convert the incoming messages to the suitable endianness before trying to process them.

Related

Update Budget Google Ads API

I am trying to update the AmoutMicros of Budget but I don't receive error, just not update the budget:
CampaignBudget budget = new CampaignBudget()
{
ResourceName = ResourceNames.CampaignBudget(customerId, budgetId),
AmountMicros = (price + amount) * 100000,
Id = budgetId
};
CampaignBudgetOperation budgetOperation = new CampaignBudgetOperation()
{
Create = budget,
UpdateMask = FieldMasks.AllSetFieldsOf(budget),
};
try
{
MutateCampaignBudgetsResponse responseBudget =
budgetService.MutateCampaignBudgets(
customerId.ToString(), new CampaignBudgetOperation[] { budgetOperation
});
foreach(MutateCampaignBudgetResult result in responseBudget.Results)
{
updateResponse.CampignId = campaignId;
updateResponse.Updated = true;
Console.WriteLine(result);
}
return updateResponse;
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
return updateResponse;
throw;
}
This code don't show me a exception, apparently it was update, but, when I go at Google Ads Dashboard, the amout still the same.
I read the documentation but I didn't find an update of a budget.
My working code is PHP but you can refer this.
private static function updateCampaignBudget(GoogleAdsClient $googleAdsClient, int $customerId,int $campaign_budget,string $budget_resource_name){
// Creates a campaign budget.
$budget = new CampaignBudget([
'resource_name' => $budget_resource_name,
//'delivery_method' => BudgetDeliveryMethod::STANDARD,
'amount_micros' => $campaign_budget
//'explicitly_shared' => false
]);
// Creates a campaign budget operation.
$campaignBudgetOperation = new CampaignBudgetOperation();
$campaignBudgetOperation->setUpdate($budget);
$campaignBudgetOperation->setUpdateMask(FieldMasks::allSetFieldsOf($budget));
// Issues a mutate request.
$campaignBudgetServiceClient = $googleAdsClient->getCampaignBudgetServiceClient();
$response = $campaignBudgetServiceClient->mutateCampaignBudgets(
$customerId,
[$campaignBudgetOperation]
);
/** #var CampaignBudget $addedBudget */
$updatedBudget = $response->getResults()[0];
//printf("Added budget named '%s'%s", $addedBudget->getResourceName(), PHP_EOL);
return $updatedBudget->getResourceName();
}
you can use ResourceNames::forCampaignBudget(customerId, budgetId) instead of $budget_resource_name

Translate from C# to PROGRESS OPENEDGE ABL

I received an C# DLL to access an API and another C# to invoke the DLL.
I'm trying to make an ABL program to INVOKE the DLL.
Ive tried the USING, also run it as an EXTERNAL but no luck.
Never used C#, but it looks like a very simple program can't find how to instatiate the DLL from ABL.
Thanks in advance,
Hugo
Here is the C# code, will appreciate any help
Code:
using System;
using System.Windows.Forms;
namespace CayanConnectSample
{
public partial class MainFrm : Form
{
public MainFrm()
{
InitializeComponent();
}
private string merchantName = "Test Dynamic Payments";
private string merchantSiteId = "2Q5JSJH3";
private string merchantKey = "GQPXT-GTJTP-66A1Y-RWT5G-CNULU";
private string terminalIPAddress = "192.168.1.32"; //ip address in CDI Technologies
private int requestTimeout = 60;
private void btnCreateTransaction_Click(object sender, EventArgs e)
{
decimal amount = Convert.ToDecimal(0.09);
string clerkId = "MIKE";
//only transactionType used are sale & refund
CayanConnect.CreateTransaction.Request request = new CayanConnect.CreateTransaction.Request()
{
MerchantName = merchantName,
MerchantSiteId = merchantSiteId,
MerchantKey = merchantKey,
TransactionType = CayanConnect.CreateTransaction.TransactionTypeEnum.SALE,
ClerkId = clerkId,
Dba = merchantName,
Amount = amount,
//[Amount] is always positive. TransactionType has the sign. Sale or Refund
OrderNumber = "1234"
};
CayanConnect.CreateTransaction createTrx = new CayanConnect.CreateTransaction();
CayanConnect.CreateTransaction.Response ctr = createTrx.Process(request, CayanConnect.ThemeEnum.None);
if (ctr.Success)
{
CayanConnect.InitiateTransaction it = new CayanConnect.InitiateTransaction(terminalIPAddress, ctr.TransportKey, null, CayanConnect.ThemeEnum.None, "Waiting for customer...");
CayanConnect.InitiateTransaction.Response response = it.Process(requestTimeout, true);
string emvDetail = response.EMVDetail;
bool approved = false;
if (response.Success)
{
//THERE IS NO TIMEOUT OR ERROR CALLING THE SERVICE
if (response.Status.ToUpper() == "APPROVED")
{
//AN AMOUNT HAS BEEN APPROVED
if (Convert.ToDecimal(Math.Abs(amount)) == response.AmountApproved)
{
//FULL AMOUNT APPROVED
approved = true;
txtResponse.Text = "Good to go!!";
}
else
{
//PARTIALLY APPROVED, HAS TO VOID THIS
string v = this.VoidApprovedTransaction(response.Token);
string em = v.IsEmpty() ? "Transaction was voided succesfully." : v;
txtResponse.Text = $"Invalid approved amount.{Environment.NewLine}Amount: {amount.ToString("C")}{Environment.NewLine}Approved Amount: {response.AmountApproved.ToString("c")}{em}";
}
}
else
{
//AMOUNT WAS DECLINED
txtResponse.Text = response.DeclinedMessage(amount);
}
}
else
{
//THERE WAS A PROBLEM CALLING THE SERVICE
txtResponse.Text = response.ErrorMessage;
}
}
else
{
//THERE WAS A PROBLEM CALLING THE SERVICE
txtResponse.Text = ctr.ErrorMessage;
}
}
private string GetStatus()
{
string rt = string.Empty;
CayanConnect.GetStatus status = new CayanConnect.GetStatus(this.terminalIPAddress, null, CayanConnect.ThemeEnum.None, "Verifying terminal status...");
CayanConnect.GetStatus.Response statusResponse = status.Process(this.requestTimeout);
rt = statusResponse.ToXml();
return rt;
}
private string VoidApprovedTransaction(string token)
{
string rt = string.Empty;
CayanConnect.Void _void = new CayanConnect.Void();
CayanConnect.Void.Request request = new CayanConnect.Void.Request()
{
MerchantName = this.merchantName,
MerchantKey = this.merchantKey,
MerchantSiteId = this.merchantSiteId,
Token = token,
Timeout = this.requestTimeout
};
CayanConnect.Void.Response response = _void.Process(request, CayanConnect.ThemeEnum.None);
if (!response.Success)
{
rt = $"Error voiding transaction.{Environment.NewLine}{Environment.NewLine}{response.ErrorMessage}";
}
return rt;
}
private void btnIsOnLine_Click(object sender, EventArgs e)
{
txtResponse.Text = GetStatus();
}
}
}
============================================================================
You don't need to 'invoke' the DLL. I have found that the DLL's doc is very important to read - you'll need to know things like who's in charge (ABL or the DLL) of memory allocation and deallocation, structure sizes etc. Also, the AVM is not re-entrant (so cannot be registered as a callback for any DLL).
For an example of calling DLL/SO functions from within an ABL class, take a look in the repo at https://github.com/PeterJudge-PSC/abl_odbc_api .
You'll need to create function prototypes (see an example at https://github.com/PeterJudge-PSC/abl_odbc_api/blob/master/src/OpenEdge/Data/ODBC/ODBCConnectionProto.i ) and you can then call those functions from within a method . Take a look at https://github.com/PeterJudge-PSC/abl_odbc_api/blob/master/src/OpenEdge/Data/ODBC/SqlCommonFunctions.cls for examples.

Live update map - Timer class - c#

I'm building a project with asp.net.
Part of the the project is a view (using google maps api) that is showing the the status of the parking lots with maerkers on the map.
Im using JSON file to create the markers.
Moreover, Im using arduino with some sensors that are indicated of the parking lot status.
I want that this Json will be update (override the previous) every 2 seconds (so that if a car enters the parking lot and now its full - it will present on the map as full)
I have 2 functions that creates this Json's and I want to call them every 2 seconds as I said before.
I could not do it. I'll be glad to receive your help.
The name of the view page: "TotalPs".
This is the controller in which the relevant function is located:
public ActionResult TotalPs()
{
ViewBag.Message = "TotalPs";
return View();
}
public ActionResult TotalPData()
{
ReadArduino(); //READ THE DATA FROM THE ARDUINO
callA(); // CREATES THE FIRST JSON
callB(); // CREATES THE 2ND JSON
var totalQueryParkingLot =
from lot in db.parkingLots
orderby lot.PricePerHour
select lot;
return Json(totalQueryParkingLot);
}
public void callA()
{
var totalQueryParkingLot =
from lot in db.parkingLots
orderby lot.PricePerHour
select lot;
var data2 = totalQueryParkingLot.ToList();
var jsonString2 = JsonConvert.SerializeObject(data2);
if (jsonString2 != null)
{
if (!Directory.Exists(Server.MapPath("~/Content/")))
{
Directory.CreateDirectory(Server.MapPath("~/Content/"));
}
}
System.IO.File.WriteAllText(Server.MapPath("~/Content/TotalJsonPL.json"), jsonString2);
}
public void callB()
{
var FreeQueryParkingLot =
from pub in db.publicParkings
orderby pub.PricePerHourpublicParking
select pub;
var data8 = FreeQueryParkingLot.ToList();
var jsonString3 = JsonConvert.SerializeObject(data8);
if (jsonString3 != null)
{
if (!Directory.Exists(Server.MapPath("~/Content/")))
{
Directory.CreateDirectory(Server.MapPath("~/Content/"));
}
}
System.IO.File.WriteAllText(Server.MapPath("~/Content/TotalJsonPU.json"), jsonString3);
}
public void ReadArduino()
{
SerialPort port = new SerialPort("COM3", 9600);
port.BaudRate = 9600;
port.PortName = "COM3";
port.Open();
bool status1 = true;
bool status2 = true;
bool status3 = true;
char[] arr = new char[4];
String data_arduino = port.ReadLine();
for (int i = 0; i < arr.Length; i++)
{
char first = data_arduino[i];
arr[i] = first;
}
int space = arr[0] - 48;
var arduinoQuery1 = from b in db.parkingLots where b.parkingLotID == 22 select b;
foreach (parkingLot parkingLot in arduinoQuery1)
{
parkingLot.freeSpaces = space;
}
db.SaveChanges();
}
In the view I call the function TotalPData() that is calling to the other functions.
Tnx!!
I am assuming that you are applying a ajax call to retrieve json data. So, you can assign interval using setInterval to execute ajax call periodically.
var interval = setInterval(ajaxCall, 5000); //5000 MS == 5 seconds
function ajaxCall() {
clearInterval(interval);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'Controller/TotalPData',
dataType: "json",
success: function (response) {
interval = setInterval(ajaxCall, 5000);
// Do something
},
error: function (a, b, c) {
}
});
}
Also, It could be better to use SignalR to perform this kind of requirements.
SignalR

using C# to get an ec2-instance tag

I'm not a developer so maybe the answer is out there for a different solution but I can't really translate it from python or something else.
I'm trying to use the AWS .NET SDK to find an instance and then get the instance's tags. I've gotten as far as being able to determine if an instance is up and running or not. I also see how I can create and delete tags (not in code example below). But I don't see an easy way to actually check if a tag exists and get the value of the tag if it does exist.
Sorry if I'm missing the obvious but this is all new to me. Here's an example of the code I'm using to check if an instance is running.
instanceID = "i-myInstanceID";
do {
var myrequest = new DescribeInstanceStatusRequest();
DescribeInstanceStatusResponse myresponse = ec2.DescribeInstanceStatus(myrequest);
int isCount = myresponse.DescribeInstanceStatusResult.InstanceStatuses.Count;
for (int isc=0; isc < isCount; isc++) {
InstanceStatus instanceStatus = myresponse.DescribeInstanceStatusResult.InstanceStatuses[isc];
if (instanceStatus.InstanceId.Contains(instanceID)) {
Console.WriteLine("It looks like instance "+instanceID+" is running.");
idIdx = isc;
foundID = true;
break;
}
}
if ((foundID==false) && (secondCounter==1)) {
Console.Write("Looking for instance "+instanceID);
} else {
Console.Write(".");
}
Thread.Sleep(1000);
secondCounter++;
if (secondCounter > 5) {
break;
}
} while (foundID == false) ;
First send a DescribeInstancesRequest to get the list of Instances:
public DescribeInstancesResult GetInstances(Ec2Key ec2Key)
{
_logger.Debug("GetInstances Start.");
AmazonEC2 ec2 = CreateAmazonEc2Client(ec2Key);
var ec2Request = new DescribeInstancesRequest();
DescribeInstancesResponse describeInstancesResponse = ec2.DescribeInstances(ec2Request);
DescribeInstancesResult result = describeInstancesResponse.DescribeInstancesResult;
_logger.Debug("GetInstances End.");
return result;
}
Then loop through the instances until you find the one you want, and then use the Tag.GetTagValueByKey method:
// This just calls the above code
DescribeInstancesResult ec2Instances = _ec2ResourceAccess.GetInstances(ec2Key);
var returnInstances = new List<Ec2UtilityInstance>();
foreach (var reservation in ec2Instances.Reservation)
{
foreach (var runningInstance in reservation.RunningInstance)
{
var returnInstance = new Ec2UtilityInstance();
returnInstance.InstanceId = runningInstance.InstanceId;
returnInstance.InstanceName = runningInstance.Tag.GetTagValueByKey("Name");
returnInstance.Status = (Ec2UtilityInstanceStatus)Enum.Parse(typeof(Ec2UtilityInstanceStatus), runningInstance.InstanceState.Name, true);
returnInstance.DefaultIp = runningInstance.Tag.GetTagValueByKey("DefaultIp");
returnInstance.InstanceType = runningInstance.InstanceType;
returnInstance.ImageId = runningInstance.ImageId;
returnInstances.Add(returnInstance);
}
}
Here is the link for full source that this was taken from:
https://github.com/escherrer/EC2Utilities
Common\Manager
and
Common\ResourceAccess

AS3 Client - C# Server Socket Connection fail,

Hi I'm working on a flash application. I'm sockets from Flash in Action-script 3 (CS5). Server is C# . My functions are nicely and great work and connect server with socket, when i export as projector (.exe). But when i export as .swf my functions are nicely work again but socket.connected return "false".
i added crossdomain.xml but still same problem.
Could you help me ?
Note: i found this page but i not load any data a external page :( .
here is my code
Edit: i didnt send to server but when i run .swf flash send a data to server
"<policy-file-request/>"
Connection Error[SecurityErrorEvent type="securityError" bubbles=false
cancelable=false eventPhase=2 text="Error #2048"]
but root include crossdomain.xml and i added this as3 kod but still problem is not solved.
Security.allowDomain("*");
Security.loadPolicyFile("http://MY-IP-ADDRESS/crossdomain.xml");
--lastest code
import flash.display.MovieClip;
import flash.display.Shape;
import flash.display.DisplayObject;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFieldType;
import flash.text.TextFieldAutoSize;
import flash.display.BitmapData;
import flash.geom.ColorTransform;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.utils.ByteArray;
import flash.net.FileReference;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.Socket;
import flash.display.BitmapData;
import flash.utils.setInterval;
import flash.system.* ;
import PNGEncoder;
public class Main extends MovieClip
{
/* Variables */
var aktarilan:BitmapData = new BitmapData(600,290);
/* Pencil Tool shape, everything drawed with this tool and eraser is stored inside board.pencilDraw */
var pencilDraw:Shape = new Shape();
/* Text format */
var textformat:TextFormat = new TextFormat();
/* Colors */
var colorsBmd:BitmapData;
var pixelValue:uint;
var activeColor:uint = 0x000000;
/* Save dialog instance */
var saveDialog:SaveDialog;
/* Active var, to check wich tool is active */
var active:String;
private static var fl_socket:Socket;
/* Shape size color */
var ct:ColorTransform = new ColorTransform();
private function onConnect(e:Event){
if(fl_socket.connected){
durum_bilgisi.text = "Connected to Server";
}else{
durum_bilgisi.text = "Connection Error";
}
}
public function Main():void
{
Security.allowDomain("*");
Security.loadPolicyFile("http://MY-IP-ADDRESS/crossdomain.xml");
fl_socket = new Socket();
fl_socket.addEventListener(Event.CONNECT, onConnect);
try{
fl_socket.connect("MY-IP-ADDRESS", 1234);
trace('Socket connection error');
}
catch(e:Error){
trace('Socket connection error ' + e.message );
durum_bilgisi.text = "Connection Error" + e.message;
}
textformat.font = "Quicksand Bold Regular";
textformat.bold = true;
textformat.size = 16;
// Soket baglantisi
convertToBMD();
addListeners();
/* Hide tools highlights */
pencil.visible = false;
hideTools(eraser, txt);
}
/* Pencil Tool */
private function PencilTool(e:MouseEvent):void
{
/* Quit active tool */
quitActiveTool();
/* Set to Active */
active = "Pencil";
/* Listeners */
board.addEventListener(MouseEvent.MOUSE_DOWN, startPencilTool);
board.addEventListener(MouseEvent.MOUSE_UP, stopPencilTool);
/* Highlight */
highlightTool(pencil);
hideTools(eraser, txt);
ct.color = activeColor;
shapeSize.transform.colorTransform = ct;
}
private function startPencilTool(e:MouseEvent):void
{
pencilDraw = new Shape();
board.addChild(pencilDraw);
pencilDraw.graphics.moveTo(mouseX, mouseY);
pencilDraw.graphics.lineStyle(shapeSize.width, activeColor, 1.0,true,"normal","round");
pencilDraw.graphics.lineTo(mouseX+1, mouseY+1);
board.addEventListener(MouseEvent.MOUSE_MOVE, drawPencilTool);
}
private function drawPencilTool(e:MouseEvent):void
{
pencilDraw.graphics.lineTo(mouseX, mouseY);
}
private function stopPencilTool(e:MouseEvent):void
{
board.removeEventListener(MouseEvent.MOUSE_MOVE, drawPencilTool);
}
/* Eraser Tool */
private function EraserTool(e:MouseEvent):void
{
var bmd:BitmapData = new BitmapData(600, 290);
bmd.draw(board);
var ba:ByteArray = PNGEncoder.encode(bmd);
/* Quit active tool */
quitActiveTool();
/* Set to Active */
active = "Eraser";
/* Listeners */
board.addEventListener(MouseEvent.MOUSE_DOWN, startEraserTool);
board.addEventListener(MouseEvent.MOUSE_UP, stopEraserTool);
/* Highlight */
highlightTool(eraser);
hideTools(pencil, txt);
ct.color = 0x000000;
shapeSize.transform.colorTransform = ct;
}
private function startEraserTool(e:MouseEvent):void
{
pencilDraw = new Shape();
board.addChild(pencilDraw);
pencilDraw.graphics.moveTo(mouseX, mouseY);
pencilDraw.graphics.lineStyle(shapeSize.width, 0xFFFFFF);
board.addEventListener(MouseEvent.MOUSE_MOVE, drawEraserTool);
}
private function drawEraserTool(e:MouseEvent):void
{
pencilDraw.graphics.lineTo(mouseX, mouseY);
}
function stopEraserTool(e:MouseEvent):void
{
board.removeEventListener(MouseEvent.MOUSE_MOVE, drawEraserTool);
}
/* Text Tool */
private function TextTool(e:MouseEvent):void
{
/* Quit active tool */
quitActiveTool();
/* Set to Active */
active = "Text";
/* Listener */
board.addEventListener(MouseEvent.MOUSE_UP, writeText);
/* Highlight */
highlightTool(txt);
hideTools(pencil, eraser);
}
private function writeText(e:MouseEvent):void
{
var textfield = new TextField();
textfield.type = TextFieldType.INPUT;
textfield.autoSize = TextFieldAutoSize.LEFT;
textfield.selectable = false;
textfield.defaultTextFormat = textformat;
textfield.textColor = activeColor;
textfield.x = mouseX;
textfield.y = mouseY;
stage.focus = textfield;
board.addChild(textfield);
}
/* Clear Tool */
private function clearBoard(e:MouseEvent):void
{
/* Create a blank rectangle on top of everything but board */
var blank:Shape = new Shape();
blank.graphics.beginFill(0xFFFFFF);
blank.graphics.drawRect(0, 0, board.width, board.height);
blank.graphics.endFill();
board.addChild(blank);
}
/* Default colors function */
private function convertToBMD():void
{
colorsBmd = new BitmapData(colors.width,colors.height);
colorsBmd.draw(colors);
}
private function chooseColor(e:MouseEvent):void
{
pixelValue = colorsBmd.getPixel(colors.mouseX,colors.mouseY);
activeColor = pixelValue;//uint can be RGB!
ct.color = activeColor;
shapeSize.transform.colorTransform = ct;
}
/* Quit active function */
private function quitActiveTool():void
{
switch (active)
{
case "Pencil" :
board.removeEventListener(MouseEvent.MOUSE_DOWN, startPencilTool);
board.removeEventListener(MouseEvent.MOUSE_UP, stopPencilTool);
case "Eraser" :
board.removeEventListener(MouseEvent.MOUSE_DOWN, startEraserTool);
board.removeEventListener(MouseEvent.MOUSE_UP, stopEraserTool);
case "Text" :
board.removeEventListener(MouseEvent.MOUSE_UP, writeText);
default :
}
}
/* Highlight active Tool */
private function highlightTool(tool:DisplayObject):void
{
tool.visible=true;
}
private function hideTools(tool1:DisplayObject, tool2:DisplayObject):void
{
tool1.visible=false;
tool2.visible=false;
}
/* Change shape size */
private function changeShapeSize(e:MouseEvent):void
{
if (shapeSize.width >= 50)
{
shapeSize.width = 1;
shapeSize.height = 1;
/* TextFormat */
textformat.size = 16;
}
else
{
shapeSize.width += 5;
shapeSize.height=shapeSize.width;
/* TextFormat */
textformat.size+=5;
}
}
private function addListeners():void
{
pencilTool.addEventListener(MouseEvent.MOUSE_UP, PencilTool);
eraserTool.addEventListener(MouseEvent.MOUSE_UP, EraserTool);
textTool.addEventListener(MouseEvent.MOUSE_UP, TextTool);
clearTool.addEventListener(MouseEvent.MOUSE_UP, clearBoard);
colors.addEventListener(MouseEvent.MOUSE_UP, chooseColor);
sizePanel.addEventListener(MouseEvent.MOUSE_UP, changeShapeSize);
shapeSize.addEventListener(MouseEvent.MOUSE_UP, changeShapeSize);
}
}
The code as you posted will not run.
// remove the following lines
fl_socket = new Socket();
fl_socket.connect("MY-IP-ADDRESS", 1234);
if(fl_socket.connected){durum_bilgisi.text = "Connected to Server";} else {durum_bilgisi.text = "Connection Error";}
// in the main function add this
fl_socket = new Socket();
fl_socket.addEventListener(Event.CONNECT, onConnect);
try{
fl_socket.connect("MY-IP-ADDRESS", 1234);
}catch(e:Error){
trace('Socket connection error ' + e.message )
}
// and lastly add this function
private function onConnect(e:Event){
if(fl_socket.connected){
durum_bilgisi.text = "Connected to Server";
}else{
durum_bilgisi.text = "Connection Error";
}

Categories

Resources