Flash Socket Programming __ Programming

Source: Internet
Author: User

Now to write a flash client, the issues to be addressed here include,

How to connect to a server,

How to listen for the contents of the server

How to send an information Server,

Now send a simple code, this code is very simple, incomplete function, in order to be able to clearly let us learn flash socket programming.

Package {import flash.net.Socket; import flash.events.*; import flash.display.Sprite; import flash.errors.*; Import Flas H.display.simplebutton; public class Client extends Sprite {private var mysocket:socket; private var host:string= "localhost"; private var port:in t=8001; Public Function Client () {Btn.addeventlistener (mouseevent.click,senddata); mysocket=new Socket (); Mysocket.addeventlistener (Event.connect,onconnect); Mysocket.addeventlistener (Ioerrorevent.io_error, Ioerrorhandler); Mysocket.addeventlistener (Progressevent.socket_data, receivedata); Mysocket.addeventlistener (Securityerror mysocket.connect (host,port);} Private Function OnConnect (e:event): void { Trace ("Connection succeeded"); Mysocket.writeutfbytes ("Test successful2/n"); Mysocket.flush ()//Send data} Private function Ioerrorhandler (e:ioerrorevent): void {trace (connection failed);} Private function Receivedata (e:progressevent): void {trace (number of bytes received +mysocket.bytesavailable); var msg:string while ( mysocket.bytesavailable) {Msg+=mysocket.readmulTibyte (mysocket.bytesavailable, "UTF8"); Trace (msg); } Private Function SendData (e:mouseevent): void {trace ("send"); Mysocket.writeutfbytes ("I am flash/n"); Mysocket.flush () ;//Send Data}}}

Let's first address the first question: (In fact, what we already have in cookbook) here is a simple demonstration

A. Connect to a server:

Mysocket=new Socket ();
Mysocket.addeventlistener (Event.connect,onconnect);

Mysocket.connect (Host,port);

Host: Is the IP side of the connection, where the connection is local so use localhost or 127.0.0.1 OK

Port: When the port number is greater than 1024, it can be basically smooth, less than 1024 and some configuration

Monitor Connection success:

Private Function OnConnect (e:event): void
{
Trace ("Connection succeeded");
Mysocket.writeutfbytes ("Test successful2/n");
Mysocket.flush ()//Send data

}

Once the connection is successful, we can send a simple message to the server:

Mysocket.writeutfbytes ("Test successful2/n");
Mysocket.flush ()//Send data

Notice that there is a/n without this carriage return, and see what happens.

Using Writeutfbytes is not possible to send data to the server immediately, but also to use the Flush method to send to the server.

two. Handling Errors:

Mysocket.addeventlistener (Ioerrorevent.io_error, Ioerrorhandler);

Private Function Ioerrorhandler (e:ioerrorevent): void
{
Trace ("Connection failed");
}

three. Information returned by the receiving server

Mysocket.addeventlistener (Progressevent.socket_data, receivedata);

Private Function Receivedata (e:progressevent): void
{
Trace ("Number of bytes received" +mysocket.bytesavailable);
var msg:string;
while (mysocket.bytesavailable)
{
Msg+=mysocket.readmultibyte (mysocket.bytesavailable, "UTF8");
Trace (msg);
}
}

So we can receive the information sent by the server, but there is a problem, receive data there will be a carriage return compliance problem, we need to solve. Not much to say here.

Look at the top.

Reference:

Bytesavailable:uint the number of bytes of data that can be read in the [read-only] input buffer readmultibyte (Length:uint, charset:string): String uses the specified character set, Reads a multibyte string from this byte stream. Four, send the message to the server question: We want to send information to the server Workaround: Use the Writeutfbytes method Private function SendData (e:mouseevent): void
{
Trace ("Send");
Mysocket.writeutfbytes ("I am flash/n");
Mysocket.flush ()//Send data
Put a button on the scene and send the message to the server socket port by clicking the button event. Reference:

Writeutfbytes (value:string): Void writes a UTF-8 string to a socket.
Five: Server programsHere a simple server program, using a simple thread, but the thread is not perfect, there are drawbacks, but does not affect the program demo:
Package com; Import java.net.*; Import java.io.*; public class Server implements Runnable {public void run () {PrintWriter os=null; try{serversocket ss=new ServerSocket (8 001); System.out.println ("Wait for connection ..."); Socket sk=ss.accept (); SYSTEM.OUT.PRINTLN ("Connection succeeded ..."); BufferedReader br = new BufferedReader (New InputStreamReader (Sk.getinputstream (), "Utf-8")); System.out.println ("Get the contents inside ..."); Waiting to receive information OS = new PrintWriter (Sk.getoutputstream ()); String Word=null; Send information while ((Word=br.readline ())!=null) {System.out.println ("content:" + word); Os.println ("Hello I am a server"); Os.flush (); } catch (IOException ex) {ex.printstacktrace ();}} public static void Main (string[] args) {new Thread (new Server ()). Start ();} Receive result: Wait for connection ....
Connection successful ....
Get the contents inside ...
Content: Test SUCCESSFUL2
Content: I am flash
Content: I am flash
Content: I am flash
Content: I am flash
Content: I am flash
To make the program more complete, we can modify the program to better improve the content of the client sent: Connection successful
Number of bytes received 16
Null Hello I am the server note: null This result, perhaps in the service appears some small brush, but the basic send data and receive data are successful procedures need to improve the place: including the client and server processing carriage return compliance problem finally found in the Var msg:string= ""; It's not going to happen if you write that null.
Add:The socket socket connection allows the Flash player to communicate with the server through the specified port, but the socket communication is not closed after the data is transmitted, and is closed artificially. We can use flash. Net. The XML socket class creates a socket connection in the XML data format, uses the Flash.net.Socket class to create a binary data format socket connection, which is lower than the XML data format, but it can connect to almost all socket server-side programs. The supplied socket links in AS3 0 are asynchronous, meaning that you must increase the event listening before you can get the data after the transmission.

To establish a socket communication, we first establish a socket connection and we can use the Socket.connect () or Xmlsocket.connect () method to establish the connection and monitor the Connect event to determine whether the connection was established. The connection requires only 2 parameters, IP, and port.

Note the condition:

SWF and host must be in the same domain;
SWF on the network cannot connect to the local server;
The local SWF cannot access any network resources;
To allow a domain name to cross access or connect to a port below 1024, you need to provide a cross-domain policy file.

If you want to access flash in different domains, you can read through Flash.system.Security.loadPolicyFile ():
Security.loadpolicyfile ("Cross-domain");
Example of a cross-domain policy file:
<?xml version= "1.0"?>
<! DOCTYPE cross-domain-policy SYSTEM "Http://www.macromedia.com/xml/dtds/cross-domainpolicy.
DTD ">
<cross-domain-policy>
<allow-access-from domain= "*" to-ports= "80,110"/>
</cross-domain-policy>

After you have established the connection, you can write to the server, by calling the Write method, you can write the data to the buffer pool, and then call the Flush () method to send the data out, this is for the binary socket, if it is XML, call the Send () method. as3.0 can define different write functions for different parameters: Writeboolean (), WriteByte (), Writebytes (),
Writedouble (), Writefloat (), Writeint (), Writemultibyte (), WriteObject (), Writeshort (), write-
Unsignedint (), writeUTF (), and Writeutfbytes (). You know the parameters that need to be passed in by the function name, and here is the Socket.writebytes (ByteArray, 0, Bytearray.length), which is described because it can pass a data and write the start and end positions of the array. , Writeutfbytes (): Writes a byte-type string, writeUTF: a numeric string. Writemultibyte () writes the string in the specified encoding, socket.writemultibyte ("Example", "Unicode");

Data is accepted after the data is sent, so we can read the data through the Progressevent.socket_data event handler, using Readboolean (): Boolean,readbyte (): Int,readdouble (): Number,readfloat (): Number,readint (): Int,readobject ():*, Readshort (): Int,readunsignedbyte (): Uint,readunsignedint (): Uint,readunsignedshort (): Uint,readutf (): String,readbytes () No return parameters, Readutfbytes () returns UTF8 data. The data received by the socket object is ASCII-encoded text, and we can reconstruct the string using the Readutfbytes () method.
The Readutfbytes () method needs to know how many bytes need to be converted and specify the number of bytes with the bytesavailable attribute:
var string:string = socket.readutfbytes (socket.bytesavailable);

The above mentioned is the use of binary socket transmission, if the way of XML, the trigger event type is different, It triggers the Dataevent.data event, and the data property of the event contains the pass-through, and if we want to read the XML we must first convert the string in data to XML format and read it.

Transferred from http://520pig.blogbus.com/logs/32821429.html

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.