2、close():void–关闭一个XMLSocket。
3、connect(host:String,port:int):void–连接到指定的TCP端口。
4、send(object:*):void–将数据发送到连接服务端。
OK,了解这些后我们就可以用XMLSocket来开发基于Socket的网络及时通信应用。下面通过C#提供一个Socket的服务端,并监听8888端口。示例程序如下:
<!–Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/–>1usingSystem;
2usingSystem.Collections.Generic;
3usingSystem.Linq;
4usingSystem.Text;
5usingSystem.Net.Sockets;
6usingSystem.IO;
7
8namespaceFlashFlexDotNet
9{
10classProgram
11{
12staticvoidMain(string[]args)
13{
14TcpListenerlistener;
15
16try
17{
18listener=newTcpListener(8888);
19}
20catch(Exceptionex)
21{
22Console.WriteLine(ex.Message);
23return;
24}
25
26listener.Start();
27Console.WriteLine(“服务器启动,等待客户端连接.”);
28boolloop=true;
29
30while(loop)
31{
32Sockets=listener.AcceptSocket();
33NetworkStreamns=newNetworkStream(s);
34StreamReaderreader=newStreamReader(ns);
35stringresult=string.Empty;
36try
37{
38result=reader.ReadLine();
39Console.WriteLine(result);
40}
41catch(Exceptionex)
42{
43Console.WriteLine(ex.Message);
44}
45}
46}
47}
48}
49
服务器端Socket已经准备完毕,下面看看客户端的ActionScript的XMLSocket怎么来建立Socket连接与.net的Socket服务端进行通信。
如本文前介绍,ActionScript 3.0提供了基于Socket的网络连接类XMLSocket,我们可以直接使用它来开发基于Socket的网络通信。如下建立一个基与ActionScript 3.0提供的XMLSocket的网络连接:
<!–Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/–>1privatefunctionconnectionServer():void
2{
3xmlConn=newXMLSocket();
4xmlConn.connect(“127.0.0.1”,8888);
5}
随后,便可以通过XMLSocket的实例方法send()向Socket服务端发送消息了。如下代码定义:
<!–Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/–>1privatefunctiononSend():void
2{
3xmlConn.send(txtData.text+”\n”);
4}
客户端完整代码:
<!–Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/–>1
2<mx:Applicationxmlns:mx="http://www.adobe.com/2006/mxml"layout="absolute"
3backgroundGradientAlphas=”[1.0,1.0]”
4backgroundGradientColors=”[#CDCAE6,#FFFFFF]”>
5
6<![CDATA[
7importmx.controls.Alert;
8
9privatevarxmlConn:XMLSocket;
10
11privatefunctionconnectionServer():void
12{
13xmlConn=newXMLSocket();
14xmlConn.connect(“127.0.0.1”,8888);
15}
16
17privatefunctiononSend():void
18{
19xmlConn.send(txtData.text+”\n”);
20}
21]]>
22
23
24
25
26