.NET C# 与Flash用AMF3 SOCKET通信

通常,使用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>



--------------------------------------------------------

//bb为byte[]二进制数据

FluorineFx.AMF3.ByteArray br = new FluorineFx.AMF3.ByteArray(new MemoryStream(bb));  
br.Position = 0;  
br.ReadShort();//amf版本
br.ReadShort();//header数量
br.ReadShort();//body数量
br.ReadUTFBytes((uint)(br.ReadShort()));//target长度和字符串  
br.ReadUTFBytes((uint)(br.ReadShort()));//Response长度和字符串  
br.ReadInt();//body长度
br.ReadByte();//body类型
object o = br.ReadObject();

 

你可能感兴趣的:(socket通信)