C#利用Fluorinefx实现使用AMF3协议与Flash通讯

通常,使用Flash来调用.NET组件需用远程调用,实际上我们也可以通过SOCKET直接通信。

具体采用Flash的AMF3或AFM0格式,采用流行的FluorineFx服务器组件,具体代码如下:

依照此用法可以开发网页游戏或其它Flash应用的.NET SOCKET服务器。


using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using FluorineFx;

namespace STCServer
{
    class Monitor
    {
        private int PORT = 8888;
        private const int MAXPKSIZE = 4096;
        private TcpListener tcpLs = null;
        private List<Client> clients = new List<Client>();

        public void Close()
        {
            if (tcpLs != null)
            {
                tcpLs.Stop();
            }
            if (clients.Count != 0)
            {
                foreach (Client c in clients)
                {
                    c.sock.Shutdown(SocketShutdown.Both);
                    c.thread.Abort();
                }
                clients.Clear();
                clients = null;
            }
        }

       private void ThreadFunc(object client)
        {
            Client ct =client as Client;
            Socket sk = ct.sock;
            byte[] cmdBuff = new byte[MAXPKSIZE];

            while (true)
            {
                try
                {
                    cmdBuff.Initialize();
                    int N =sk.Receive(cmdBuff);
                    Console.WriteLine(DateTime.Now.ToString()+":接收数据成功,长度:"+N );

                    System.IO.MemoryStream ms = new System.IO.MemoryStream(cmdBuff, 0, N);
                    FluorineFx.AMF3.ByteArray ba = new FluorineFx.AMF3.ByteArray(ms);                                      
                    Node o = (Node)ba.ReadObject();
                    Console.WriteLine(o.ID);
                    Console.WriteLine(o.Name);
                    Console.WriteLine(o.Address);
                    o.Name = "张三";
                    Node node = new Node();
                    node.ID = o.ID;
                    node.Name = o.Name;
                    node.Address = o.Address;

                    FluorineFx.AMF3.ByteArray result = new FluorineFx.AMF3.ByteArray();
                    result.WriteObject(node);
                    byte[] buf = new byte[result.Length];
                    result.Position = 0;
                    result.ReadBytes(buf, (uint)0, (uint)buf.Length);
                    foreach (Client cl in clients)
                    {                      
                        cl.sock.Send(buf,buf.Length,SocketFlags.None);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("网络终止:" + e.Message);
                    ct.sock.Shutdown(SocketShutdown.Both);
                    clients.Remove(ct);
                    Thread.CurrentThread.Abort();
                    ct = null;
                }
            }
        }
        public void StartUp()
        {
            IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName())[0];
            tcpLs = new TcpListener(ip, PORT);
            tcpLs.Start();
            while (true)
            {
                byte[] packetBuff = new byte[MAXPKSIZE];
                Console.WriteLine("服务器已启动,正在监听.../n");
                Console.WriteLine(string.Format("服务器IP:{0}/t端口号:{1}/n", ip, PORT));

                Socket sk = tcpLs.AcceptSocket();
                Console.WriteLine("已经连接,接收数据.../n");
                Thread cth = new Thread(new ParameterizedThreadStart(ThreadFunc));
                Client cl = new Client(sk,cth);
                clients.Add(cl);              
                cth.Start(cl);
            }
        }
    }
}

namespace STCServer
{
    class Client
    {
        public Socket sock=null;
        public Thread thread = null;
        public Client(Socket s, Thread th)
        {
            sock = s;
            thread = th;
        }

    }
}


namespace STCServer
{
    public class Node
    {
        public uint ID;
        public string Name;
        public string Address;
    }
}



Flash(FLEX)客户端:

package
{
import flash.events.*;
import flash.net.ObjectEncoding;
import flash.net.Socket;
import flash.net.registerClassAlias;
import flash.utils.ByteArray;
public class Greeter
{
  private var socket :Socket;
     public function sayHello():void

        {
         registerClassAlias("STCServer.Node",Node);
         socket = new Socket();
         socket.addEventListener(Event.CONNECT,onHandler);
         socket.addEventListener(ProgressEvent.SOCKET_DATA, onHandler);  

         socket.objectEncoding=ObjectEncoding.AMF3;
         socket.connect("192.168.1.14",8888);
         var node:Node=new Node();
         node.ID=122;
         node.Name="用户名";
         node.Address="kkkkkkk";
         var num:Number;
         trace(num);
         var arr:ByteArray=new ByteArray;
         arr.writeObject(node);
         arr.compress();
         socket.writeBytes(arr);
         socket.flush();
}

  public function  onHandler(event:Event):void
  {
   switch(event.type) {  
                case ProgressEvent.SOCKET_DATA:
                 trace(new Date());
                 trace("数据接受成功");  
                    var bytes:ByteArray = new ByteArray();  
                    socket.readBytes(bytes);  
                    bytes.uncompress();  
                    var node:Node;
                    node=Node(bytes.readObject());
                    trace(node.Name);
                    trace(node.ID);
                    trace(node.Address);  
                    break;  
                case Event.CLOSE:  
                    trace("连接关闭");  
                    break;  
                case Event.CONNECT:  
                    trace("连接䶿..");  
                    break;  
                case IOErrorEvent.IO_ERROR:  
                case SecurityErrorEvent.SECURITY_ERROR:  
                    trace("连接失败");  
                    break;  
            }    
  }
}
}

package
{
public class Node
{
  public var ID :uint;
   public var Name :String;
   public var Address :String;
   public function Node()
  {
  }
}
}


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*"
    layout="vertical"
    creationComplete = "initApp()" >
    
    <mx:Script>
        <![CDATA[
            private var myGreeter:Greeter = new Greeter();
            
            public function initApp():void
            {
                // says hello at the start, and asks for the user's name
                mainTxt.text = myGreeter.sayHello();
            }
        ]]>
    </mx:Script>

    <mx:TextArea id = "mainTxt" width="400" />        
    
</mx:Application>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值