• AS3SOCKET 转贴


    //-------------
    //
    Base64和StringUtil在网上自己找吧
    import Base64;
    import StringUtil;
    var socket = new Socket();
    socket.connect(
    "localhost"11915);

    socket.addEventListener(Event.CLOSE, closeHandler);
    socket.addEventListener(Event.CONNECT, connectHandler);
    socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
    socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
    socket.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);

    var response:String;

    function writeln(str:String):void {
     str 
    += "";
     
    try {
      socket.writeUTFBytes(str);
     } 
    catch (e:IOError) {
      trace(e);
     }
    }

    function sendRequest():void {
     trace(
    "sendRequest");
     response 
    = "";
     writeln(
    'bin');
     socket.flush();
    }

    function readResponse():void {
    //接受数据
     var str:String = socket.readUTFBytes(socket.bytesAvailable);
     response 
    += str;
    //当数据以end结束的时候,数据传输结束
     if(StringUtil.endsWith(str,'end'))
     {
      response 
    = response.substr(0,response.length-3);
    //把字符串转换为ByteArray
      var ba = Base64.decodeToByteArray(response);
      
    //trace('bytearray=====',ba);
      var l:Loader = new Loader();
    //从 ByteArray 对象中所存储的二进制数据中加载。
      l.loadBytes(ba);
      
    //trace(l.content);
      addChild(l);
     }
    }


    function closeHandler(event:Event):void {
     trace(
    "closeHandler: " + event);
    }

    function connectHandler(event:Event):void {
     trace(
    "connectHandler: " + event);
     sendRequest();
    }

    function ioErrorHandler(event:IOErrorEvent):void {
     trace(
    "ioErrorHandler: " + event);
    }

    function securityErrorHandler(event:SecurityErrorEvent):void {
     trace(
    "securityErrorHandler: " + event);
    }

    function socketDataHandler(event:ProgressEvent):void {
     trace(
    "socketDataHandler: " + event);
     readResponse();
    }

    <?php
    //error_reporting(E_ALL);
    error_reporting(0);
    set_time_limit(0);

    ob_implicit_flush();

    $address = 'localhost';
    $port = 11915;

    if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
    echo "socket_create() failed: reason: " . socket_strerror($sock. ""n";
    }

    if ((
    $ret = socket_bind($sock$address$port)) < 0) {
    echo 
    "socket_bind() failed: reason: " . socket_strerror($ret) . ""n";
    }

    if (($ret = socket_listen($sock, 5)) < 0) {
    echo "socket_listen() failed: reason: " . socket_strerror($ret. ""n";
    }
    echo 
    "connect.";
    do {
    if ((
    $msgsock = socket_accept($sock)) < 0) {
    echo 
    "socket_accept() failed: reason: " . socket_strerror($msgsock) . ""n";
    break;
    }

    do {

      socket_recv(
    $msgsock, $buf, 2048, 0);
      
    if ($buf == '') {
    socket_close(
    $msgsock);
        
    echo "some one quit";
    break;
    }
      
    else if($buf == 'bin')
      {
    //读取主程序数据
       $f = fopen('main.swf','r');
       
    $data = fread($f,filesize('main.swf'));
       
    fclose($f);
    //转换为字符串
       //echo base64_encode($data);

       $talkback = base64_encode($data).'end';
      }
    //发送
    socket_send($msgsock, $talkback, strlen($talkback),0);
    while (true);
    socket_close(
    $msgsock);
    while (true);

    socket_close(
    $sock);
    ?>

    /***************************************
     * 对象名称: SocketObj
     * 功能说明: 远程发送与接收
     * 试用示例:
     *           using EC;  //引用空间名
     *           string url = "218.75.111.74";   // URL也可以是(http://www.baidu.com/)这种形式
     *           int port = 8000;    //端口
     *           string SendStr = "domainname\n"; //组织要发送的字符串
     *           SendStr += "check\n";
     *           SendStr += "entityname:domains\n";
     *           SendStr += "domainname:" + this.TextBox1.Text + "\n";
     *           SendStr += ".\n";
     *           EBSocketObj o = new SocketObj();  //创建新对象
     *           o.Connection(url, port);                //打开远程端口
     *           o.Send(SendStr);                     //发送数据
     *           Response.Write(o.Recev()); //接收数据
     *           o.Dispose(); //销毁对象

    **********************************************/

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;

    namespace EC
    {
        /// <summary>
        /// Socket 远程发送与接收
        /// </summary>
        public class SocketObj
        {
            private NetworkStream ns;
            private bool _alreadyDispose = false;

            #region 构造与释构
            public EBSocketObj()
            {
                //
                // TODO: 在此处添加构造函数逻辑
                //
            }
            public EBSocketObj(string url, int port)
            {
                Connection(url, port);
            }
            ~EBSocketObj()
            {
                Dispose();
            }
             protected virtual void Dispose(bool isDisposing)
            {
                if (_alreadyDispose) return;
                if (isDisposing)
                {
                    if (ns != null)
                    {
                        try
                        {
                            ns.Close();
                        }
                        catch (Exception E) { }
                        ns.Dispose();
                    }
                }
                _alreadyDispose = true;
            }
            #endregion

            #region IDisposable 成员

            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
            #endregion

            #region 打开端口
            /// <summary>
            /// 打开端口
            /// </summary>
            /// <param name="url">URL或者:IP地址</param>
            /// <param name="port"></param>
            /// <returns></returns>
            public virtual void Connection(string url, int port)
            {
                if (url == null || url == "") return;
                if (port < 0) return;
                if (port.ToString()==string.Empty) port = 80;
                TcpClient tcp = null;
                try
                {
                    tcp = new TcpClient(url, port);
                }
                catch (Exception E)
                {
                    throw new Exception("Can't connection:" + url);
                }
                this.ns = tcp.GetStream();
            }
            #endregion

            #region 发送Socket
            /// <summary>
            /// 发送Socket
            /// </summary>
            /// <param name="ns"></param>
            /// <param name="message"></param>
            /// <returns></returns>
            public virtual bool Send(string message)
            {
                if (ns == null) return false;
                if (message == null || message == "") return false;
                byte[] buf = Encoding.ASCII.GetBytes(message);
                try
                {
                    ns.Write(buf, 0, buf.Length);
                }
                catch (Exception E)
                {
                    throw new Exception("Send Date Fail!");
                }
                return true;
            }
            #endregion

            #region 收取信息
            /// <summary>
            /// 收取信息
            /// </summary>
            /// <param name="ns"></param>
            /// <returns></returns>
            public string Recev()
            {
                if (ns == null) return null;
                byte[] buf = new byte[4096];
                int length = 0;
                try
                {
                    length = ns.Read(buf, 0, buf.Length);
                }
                catch (Exception E)
                {
                    throw new Exception("Receive data fail!");
                }
                return Encoding.ASCII.GetString(buf, 0, length);
            }
            #endregion

       }
    }

    socket.Send(bytes,0 , bytes.Length , SocketFlags.None);

  • 相关阅读:
    (二)ABP+MetroNic--- 用户管理及角色管理的实现
    BootstrapValidator 自定义服务端验证
    ASP.Net Web API 的参数绑定[翻译]
    ABP webapi IDInput传参
    JqueryTable ServerSide Ajax 数据加载及样式设置
    JqueryTable踩过的坑
    Lambda 表达式中 动态解析OrderbyLinQ语句的实现
    jenkins问题整理
    maven profile实现多环境配置
    Spring 发送内嵌图片的邮件 遇到的问题
  • 原文地址:https://www.cnblogs.com/appleseed/p/1269645.html
Copyright © 2020-2023  润新知