Flex and twisted via socket communication

Source: Internet
Author: User
Tags addchild join socket connect socket error xmlns port number

Flex-Side Code

<?xml version= "1.0" encoding= "Utf-8"?> <mx:application xmlns:mx= "Http://www.adobe.com/2006/mxml" xmlns: Simple= "simple.*" layout= "absolute" horizontalalign= "center" verticalalign= "middle" width= "850" height= "510" horizontalscrollpolicy= "Off" verticalscrollpolicy= "Off" applicationcomplete= "Init ();" > <mx:Script> <!--[cdata[import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import Flash.events.SecurityErrorEvent; Import Flash.net.Socket; Import Flash.utils.ByteArray; Import Mx.containers.Canvas; Import Mx.controls.Alert; Import Mx.controls.Image; Import Mx.controls.TextArea; Import Mx.effects.Move; public var osocket:socket = new Socket (); [Bindable] public var nickname:string = '; Initialize, listen for socket event Private Function init (): void {security.allowdomain ("*");//Monitor Socket Event Osocket.addeventlistener ( event.close,fooclosed); Osocket.addeventlistener (event.connect,fooconnected); Osocket.addeventlistener (Ioerrorevent.io_error,fooerror); Osocket.addeventlisteneR (securityerrorevent.security_error,foosecurity); Osocket.addeventlistener (Progressevent.socket_data,foogetdata); }//Connection Shutdown Event Response public Function fooclosed (e:event): void{alert.show (' connection disconnected. ', ' disconnected '); Game.setvisible (FALSE); Login.setvisible (TRUE); }//Login Status Event response public function fooconnected (e:event): void{alert.show (' Security error: 111111 '); text_c.setvisible (false); Btn_ Connect.enabled = true; Login.setvisible (FALSE); Game.setvisible (TRUE); }//socket Error Event response public Function Fooerror (e:ioerrorevent): void{alert.show (' IO error: ' +e.text, ' Socket connect error '); Text_c.text = ' Socket connect error! '; Btn_connect.enabled = true; }//Security sandbox Incident Response public Function foosecurity (e:securityerrorevent): void{alert.show (' Security error: ' +e.text ' Text_c.text = ' Security error! '; Btn_connect.enabled = true; }//Retrieve the return information from the server and perform different processing according to different protocol numbers public function foogetdata (e:progressevent): void{alert.show (' Security error: 22222 '); var amsg: Array = []; while (osocket.bytesavailable) {Amsg.push (Osocket.readmultibyte (osocket.bytesAvailable, ' utf-8 ')); } var smsg:string = Amsg.join ("). Replace (//r/g,"); if (Smsg.indexof ('::: ')!=-1) {var arr:array; var arr1:string; var Arr2:array; var Play:array; var I:int; ARR = Smsg.split ('::: '); Fooshowmsg (Arr[0]); ARR1 = arr[1] Arr2 = Arr1.split (' * * * '); for (i=0;i<arr2.length;i++) {play = Arr2[i].split ('---');//Check if the player already exists var tempobj:object = Game.getchildbyname (play[ 0]); if (tempobj = = null) {//Draw player container var People:canvas = new Canvas (); people.name = play[0]; people.id = play[0]; people.x = Play [1]; People.y = play[2]; People.width = 80; People.height = 100; Game.addchild (people); Draw the player name var Playername:label = new Label (); Playername.text = play[0]; playername.x = 15; Playername.y = 5; People.addchild (PlayerName); Draw player picture var player:image = new Image (); player.name = ' img ' +play[0]; Player.id= ' img ' +play[0]; Player.x = 10; Player.y = 20; Player.width = 64; Player.height = 64; Player.source = '. /images/' +play[3]+ '. png '; People.addchild (player); If you are yourself, label the coordinates if (play[0]==nicknAME) {pos.text = ' current coordinates: (' +play[1]+ ', ' +play[2]+ ') '; }}}}else if (Smsg.indexof (' pos ')!=-1) {//player moves var arr:array; var arr2:array; arr = Smsg.split (': '); arr2 = Arr[1].split ( '---'); if (arr2[0]==nickname) {//Do not handle}else{//mobile var theplayer:object = Game.getchildbyname (arr2[0]); MoveTo (THEPLAYER,ARR2 [1],arr2[2]}}else{fooshowmsg (SMSG);}} Display Chat Information public function fooshowmsg (smsg:string): void{var stemp:string = msg.text; msg.text = stemp+smsg;//Chat box automatically scroll to the bottom m Sg.verticalscrollposition = msg.maxverticalscrollposition; }//Send message to server public function Foocommand (smsg:string): void{var bmsg:bytearray = new ByteArray (); if (smsg.length>0) {BM Sg.writeutfbytes (smsg+ "); Bmsg.writeutfbytes ('/r/n '); Osocket.writebytes (BMSG); Osocket.flush (); }}//Send chat Public function sendchat (msg:string): void{var tempmsg:string = ' [' +nickname+ ']: ' +msg; Foocommand (tempmsg); Put.text= "; Alert.show ("AAA")}//Login connection Game Public Function Fooconnect (): void{var sip:string = Ip_text.text; var sport:number = number (POrt_text.text); var suser:string = User_text.text; var scode:string = Code_text.text; var splayer:string = User_name.text; if (! ( Sip&&sport)) {alert.show (' server address and port number required. ', ' Warning: '); }else{text_c.text = ' connecting ... '; text_c.setvisible (true);//btn_connect.enabled = false; Osocket.connect (SIP, SPort); if (suser) foocommand (' user ' +suser); if (sCode) foocommand (' Pass ' +scode); if (splayer) Foocommand (' Player: ' +splayer); Nickname = User_name.text; }}//Break link, exit game public Function Foodisconnect (): void{osocket.close (); game.setvisible (false); login.setvisible (true);} The player moves his or her private Function moveplayer (): void {var x:int = mouseX-64; var y:int = mouseY-90; if (y<43) {y = n;} if (Y&gt ; 255 && x<195) {return;}//Send the latest coordinates to the server Foocommand (' pos: ' +nickname+ '---' +x+ '---' +y); Pos.text = ' Current coordinates: (' +x+ ', ' +y+ ') '; var myself:object = game.getchildbyname (nickname); MoveTo (Myself,x,y); }//Mobile player Private Function MoveTo (obj:object,x:int,y:int): void{var move:move = new Move (obj); move.duration = 1000; Move.xto = x; Move.yto = y; Move.play (); }]]--> </mx:Script> <mx:panel width= "382" height= "260" layout= "absolute" title= "MMORPG DEMO" Horizontalcenter= "0" verticalcenter= " -26" id= "Login" visible= "true" > <mx:label x= "ten" y= "text=" Server address: * " Width= "fontsize=" textalign= "right"/> <mx:label x= "Ten" y= "text=" Port: * "width=" "fontsize=" 12 " textalign= "right"/> <mx:label x= "Ten" y= "five" text= "User name:" width= "" "fontsize=" three "textalign=" right "/> <mx: Label x= "y=" 108 "text=" Password: "fontsize=" width= "" "textalign=" "right"/> <mx:label x= "Ten" y= "136" text= "role name:" F Ontsize= "width=" textalign= "right"/> <mx:button x= "123" y= "186" label= "Login" fontsize= "width=" Btn_connect "click=" Fooconnect () "/> <mx:textinput x=" 120.5 "y=" "text=" 127.0.0.1 "width=" and "borderstyle=" Inset "bordercolor=" #B7BABC "id=" Ip_text "/> <mx:textinput x=" 120.5 "y=" the "text=," 8555 "width=" "id=" Port_text "/> <mx:textinpuT x= "120.5" y= "width=" "id= user_text"/> "<mx:textinput" x= "120.5" y= "108" width= "" displayaspassword= " True "id=" Code_text "/> <mx:textinput x=" 120.5 "y=" 136 "width=" "id=" user_name "text=" Guest "/> <mx:text x = "y=" "166" text= "Connecting ..." width= "170.5" color= "#16AD21" id= "Text_c" visible= "false"/> </mx:panel > <mx:panel backgroundattachment= "fixed" width= "horizontalscrollpolicy=" "Off" verticalscrollpolicy= "off" height= "layout=" Absolute "title=" [{Nickname}]-MMORPG DEMO "horizontalcenter=" 0 "id=" Game "visible=" false " Bordercolor= "#9B8F28" borderstyle= "None" mousedown= "Moveplayer ();" verticalcenter= "0" > <mx:textarea x= "1" y= " 325 "width=" 225 "height=" "id=" MSG "editable=" false "color=" #E0630F "bordercolor=" #735211 "text=" "borderstyle=" Inset "fontsize=" "fontfamily=" Verdana "/> <mx:textinput x=" 2 "y=" 436 "width=" 224 "id=" input "enter=" Sendchat ( Input.text) "bordercolor=" #EC6E08 "color=" #042830 "fontsize="/> &LT;mx:label x= "639" y= "ten" width= "131" height= "id=" "pos" alpha= "1.0" color= "#F05C03"/> </mx:Panel> </mx: Application>

Twisted-side code

#-*-Coding:utf-8-*-#Twisted MMORPG from twisted.internet.protocol import Factory from twisted.protocols.basic Import Lineonlyreceiver from twisted.internet Import reactor import random Import String Class Game (lineonlyreceiver): Def linere Ceived (self, data): Self.factory.sendAll ('%s '% (data)) def getId (self): return str (Self.transport.getPeer ()) def Connectionmade (self): print "New User Login:", Self.getid () self.transport.write ("<?xml version=/" 1.0/"? ><! DOCTYPE cross-domain-policy SYSTEM/"/xml/dtds/cross-domain-policy.dtd/" ><cross-domain-policy>< Site-control permitted-cross-domain-policies=/"master-only/"/><allow-access-from domain=/"* *" to-ports=/"* * "/></cross-domain-policy>/0") Self.transport.write ("Welcome to the MMO World.") /n ") self.factory.addClient (self) def connectionlost (self, Reason): Self.factory.delClient (Self) class gamefactory ( Factory): protocol = Game def __init__ (self): self.clients = [] Self.player = [] self.msg = ' self.x = range (100, 700) SELF.Y = Range (+) def getplayerid (self): return Len (Self.player) def addclient (self, newclient): Self.clients.appe nd (newclient) def delclient (self, client): Self.clients.remove (client) def sendall (self, data): Print data if Data.find (' <policy-file-request/> ')! = -1:self.clients[0].transport.write (' <cross-domain-policy>< Allow-access-from domain= "*" to-ports= "*"/></cross-domain-policy>/0 ') Else:arr = Data.split (': ') prefix = arr [0] content = arr[1] If Prefix.find (' Player ')! = -1:newplayer = [content, str (random.randrange (+)), str (Random.ran Drange (), str (Random.randrange (1, 5))] Self.player.append (newplayer) self.msg = ' Player ' + content + ' Enter the game! ' #广播所有 Player's position temp = [] Playerdata = '::: ' for POS in Self.player:temp.append (String.Join (POS, '---')) Playerdata = Playerdata + String.Join (temp, ' * * * ') self.clients[0].transport.write (' [System]: ' + self.msg + '/n ') Self.clients[0].transport.write ( Playerdata) elif prefix.find (' pos ')! = -1:playername, x, y = content.split ('---') i = 0 for P in self.player:if p[i][0] = = Playername:p[i][1] = x p[i][2] = y for Proto in S Elf.clients:proto.transport.write (data) else:self.msg = data for Proto in Self.clients:proto.transport.write (self.msg + '/n ') reactor.listentcp (8555, Gamefactory ()) Reactor.run ()

The above code returns the contents of Crossdomain directly to flex via the server side. As already mentioned in the previous article, Flex will ask for information on whether or not the Crossdomain is returned under the port 843, so you can resolve the issue of Flex cross-domain (8043 security sandbox) by deploying a service with Port 843

The service code for Port 843 is:

From twisted.internet Import reactor from Twisted.internet.protocol import Factory, protocol class Policysocketprotocol ( Protocol): Def datareceived (self, data): Self.transport.write ("<?xml version=/" 1.0/"? ><! DOCTYPE cross-domain-policy SYSTEM/"/xml/dtds/cross-domain-policy.dtd/" ><cross-domain-policy>< Site-control permitted-cross-domain-policies=/"master-only/"/><allow-access-from domain=/"* *" to-ports=/"* * "/></cross-domain-policy>/0") class Policyfactory (Factory): def __init__ (self): Self.protocol = Policysocketprotocol; if __name__ = = ' __main__ ': reactor.listentcp (843, Policyfactory (), interface= "127.0.0.1") Reactor.run ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.