예제 #1
0
파일: Util.cs 프로젝트: jinyuttt/netudt
        //public static string hexString(MessageDigest digest){
        //   //byte[] messageDigest = digest.digest();
        //   //StringBuilder hexString = new StringBuilder();
        //   //for (int i=0;i<messageDigest.length;i++) {
        //   //	String hex = Integer.toHexString(0xFF & messageDigest[i]);
        //   //	if(hex.length()==1)hexString.append('0');
        //   //	hexString.append(hex);
        //   //}
        //   //return hexString.toString();
        //   return "";
        //}


        /// <summary>
        /// 接收文件
        /// </summary>
        /// <param name="fos">文件写入流</param>
        /// <param name="inStream">网络接收流</param>
        /// <param name="size">文件大小</param>
        /// <param name="flush">是否及时刷新</param>
        public static void CopyFileReceiver(FileStream fos, UDTInputStream inStream, long size, bool flush)
        {
            byte[] buf = new byte[8 * 65536];
            int    c;
            long   read = 0;

            while (true)
            {
                c = inStream.Read(buf, 0, buf.Length);
                if (c < 0)
                {
                    break;
                }
                read += c;
                Console.WriteLine("writing <" + c + "> bytes");
                fos.Write(buf, 0, c);
                if (flush)
                {
                    inStream.Flush();
                }
                if (read >= size && size > -1)
                {
                    break;
                }
            }
            if (!flush)
            {
                inStream.Flush();
            }
        }
예제 #2
0
 /// <summary>
 /// copy input data from the source stream to the target stream
 /// 用在接收文件
 /// </summary>
 /// <param name="source">input stream to read from</param>
 /// <param name="target">output stream to write to</param>
 /// <param name="size">要接收的总长度</param>
 /// <param name="flush">每次写入后是否清除此流的缓冲区</param>
 public static void copy(UDTInputStream source, FileStream target, long size, bool flush)
 {
     try
     {
         byte[] buf = new byte[512 * 1024];
         int    c;
         int    read = 0;
         while (true)
         {
             c = source.Read(buf, 0, buf.Length);
             if (c < 0)
             {
                 break;
             }
             else if (c > 0)
             {
                 read += c;
                 ///Log.Write("writing <"+c+"> bytes");
                 target.Write(buf, 0, c);
                 if (flush)
                 {
                     target.Flush();
                 }
                 if (read >= size && size > -1)
                 {
                     break;
                 }
             }
             Thread.Sleep(50);
         }
         if (!flush)
         {
             target.Flush();
         }
     }
     catch (Exception exc)
     {
         Log.Write("copy-ReceiveFile", exc);
     }
 }
예제 #3
0
파일: Util.cs 프로젝트: jinyuttt/netudt
        /**
         * read a line from the given input stream
         * @param input - the input stream
         * @param terminatorChar - the character used to terminate lines
         * @return the line read or <code>null</code> if end of input is reached
         * @throws IOException
         */
        public static string ReadLine(UDTInputStream input, char terminatorChar)
        {
            MemoryStream bos = new MemoryStream();

            while (true)
            {
                int c = input.Read();
                if (c < 0 && bos.Length == 0)
                {
                    return(null);
                }
                if (c < 0 || c == terminatorChar)
                {
                    break;
                }
                else
                {
                    bos.Write(BitConverter.GetBytes(c), 0, 4);
                }
            }
            return(bos.Length > 0? Encoding.Default.GetString(bos.ToArray()): null);
        }
예제 #4
0
파일: Util.cs 프로젝트: jinyuttt/netudt
 /**
  * read a line terminated by a new line '\n' character
  * @param input - the input string to read from
  * @return the line read or <code>null</code> if end of input is reached
  * @throws IOException
  */
 public static string ReadLine(UDTInputStream input)
 {
     return(ReadLine(input, '\n'));
 }
예제 #5
0
 /**
  * copy input data from the source stream to the target stream
  * @param source - input stream to read from
  * @param target - output stream to write to
  * @throws IOException
  */
 public static void copy(UDTInputStream source, FileStream target)
 {
     copy(source, target, -1, false);
 }
예제 #6
0
        public void run(object stateInfo)
        {
            TaskInfo ti        = (TaskInfo)stateInfo;
            bool     memMapped = false;

            try
            {
                Log.Write("Handling request from " + ti.socket.getSession().getDestination());
                UDTInputStream  inputStream  = ti.socket.getInputStream();
                UDTOutputStream outputStream = ti.socket.getOutputStream();
                byte[]          readBuf      = new byte[32768];

                //read file name info
                while (inputStream.Read(readBuf, 0, readBuf.Length) == 0)
                {
                    Thread.Sleep(100);
                }
                ByteBuffer bb = new ByteBuffer(readBuf);
                //how many bytes to read for the file name
                //byte[] len = new byte[4];
                byte[] len = bb.PopByteArray(4);
                if (ti.verbose)
                {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < len.Length; i++)
                    {
                        sb.Append(len[i].ToString());
                        sb.Append(" ");
                    }
                    Log.Write("[SendFile] name length data: " + sb.ToString());
                }
                long length = Util.decode(len, 0);
                if (verbose)
                {
                    Log.Write("[SendFile] name length     : " + length);
                }
                //byte[] fileName = new byte[(int)length];
                byte[] fileName  = bb.PopByteArray((int)length);
                string sfileName = Encoding.Default.GetString(fileName);
                if (!File.Exists(sfileName))
                {
                    Log.Write("[SendFile] Send the file does not exist : " + sfileName);
                    return;
                }

                FileStream fis = new FileStream(sfileName, FileMode.Open, FileAccess.Read);
                Log.Write("[SendFile] File requested: " + sfileName);
                try
                {
                    long size = fis.Length;
                    Log.Write("[SendFile] File size: " + size);
                    //send size info
                    outputStream.Write(Util.encode64(size), 0, 8);
                    outputStream.Flush();

                    //( System.DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks)/10000;
                    //如果要得到Java中 System.currentTimeMillis() 一样的结果,就可以写成 上面那样,也可以这样写:
                    // TimeSpan ts=new TimeSpan( System.DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks);
                    //(long)ts.TotalMilliseconds;
                    TimeSpan ts_start = new TimeSpan(System.DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks);
                    long     start    = (long)ts_start.TotalMilliseconds;

                    //and send the file
                    if (memMapped)
                    {
                        copyFile(fis, outputStream);
                    }
                    else
                    {
                        Util.copySend(fis, outputStream, size, false);
                    }
                    while (true)
                    {
                        //UDTSender _udtsender = ti.socket.getSender();
                        //if (_udtsender.GetsendQueueCount() == 0)
                        UDTSession _udtsession = ti.socket.getSession();
                        if (_udtsession.getState() == 4)
                        {
                            break;
                        }
                        else
                        {
                            Thread.Sleep(2000);
                        }
                    }
                    Log.Write("[SendFile] Finished sending data.");

                    TimeSpan ts_end = new TimeSpan(System.DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks);
                    long     end    = (long)ts_end.TotalMilliseconds;

                    Log.Write(ti.socket.getSession().getStatistics().toString());
                    double rate = 1000.0 * size / 1024 / 1024 / (end - start);
                    Log.Write("[SendFile] Rate: " + Math.Round(rate, 3) + " MBytes/sec. " + Math.Round(8 * rate, 3) + " MBit/sec.");
                }
                finally
                {
                    ti.socket.getSender().stop();
                    ti.socket.close();
                    if (fis != null)
                    {
                        fis.Close();
                    }
                }
                Log.Write("Finished request from " + ti.socket.getSession().getDestination());
            }
            catch (Exception ex)
            {
                Log.Write("[SendFile] File err", ex);
            }
        }
예제 #7
0
        public void RunReceive()
        {
            verbose = true;
            try
            {
                UDTReceiver.connectionExpiryDisabled = true;
                //IPAddress myHost = null;
                //if (localIP != "")
                //{
                //    myHost = IPAddress.Parse(localIP);
                //}
                //else
                //{
                //    string hostname = Dns.GetHostName();
                //    IPHostEntry hostip = Dns.GetHostEntry(hostname);
                //    foreach (IPAddress ipaddress in hostip.AddressList)
                //    {
                //        if (ipaddress.ToString().IndexOf(':') < 0)//存在IPV6的地址,所以要判断
                //        {
                //            myHost = ipaddress;
                //            break;
                //        }
                //    }
                //}
                UDTClient client = new UDTClient(localPort);
                client.connect(serverHost, serverPort);
                UDTInputStream  inputStream  = client.getInputStream();//报错未将对象引用设置到对象的实例。
                UDTOutputStream outputStream = client.getOutputStream();

                Log.Write(this.ToString(), "[ReceiveFile] Requesting file " + remoteFile);

                byte[] fName = Encoding.Default.GetBytes(remoteFile);

                //send file name info
                byte[] nameinfo = new byte[fName.Length + 4];
                System.Array.Copy(Util.encode(fName.Length), 0, nameinfo, 0, 4);
                System.Array.Copy(fName, 0, nameinfo, 4, fName.Length);

                outputStream.Write(nameinfo, 0, nameinfo.Length);
                outputStream.Flush();
                //pause the sender to save some CPU time
                outputStream.pauseOutput();

                //存放文件长度信息
                byte[] sizeInfo = new byte[8];

                int total = 0;
                while (total < sizeInfo.Length)
                {
                    int r = inputStream.Read(sizeInfo, 0, sizeInfo.Length);
                    if (r < 0)
                    {
                        break;
                    }
                    total += r;
                    Thread.Sleep(50);
                }
                long size = Util.decode(sizeInfo, 0);

                if (File.Exists(localFile))
                {
                    File.Delete(localFile);
                }

                Log.Write(this.ToString(), "[ReceiveFile] Write to local file <" + localFile + ">");

                FileStream os = new FileStream(localFile, FileMode.Create, FileAccess.Write);
                try
                {
                    Log.Write(this.ToString(), "[ReceiveFile] Reading <" + size + "> bytes.");
                    //( System.DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks)/10000;
                    //如果要得到Java中 System.currentTimeMillis() 一样的结果,就可以写成 上面那样,也可以这样写:
                    // TimeSpan ts=new TimeSpan( System.DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks);
                    //(long)ts.TotalMilliseconds;
                    TimeSpan ts_start = new TimeSpan(System.DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks);
                    long     start    = (long)ts_start.TotalMilliseconds;

                    //接收文件数据
                    Util.copy(inputStream, os, size, false);

                    client.shutdown();

                    TimeSpan ts_end = new TimeSpan(System.DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks);
                    long     end    = (long)ts_end.TotalMilliseconds;

                    double rate = 1000.0 * size / 1024 / 1024 / (end - start);    //接收所用时间

                    Log.Write(this.ToString(), "[ReceiveFile] Rate: " + Math.Round(rate, 3) + " MBytes/sec. " + Math.Round(8 * rate, 3) + " MBit/sec.");



                    if (verbose)
                    {
                        Log.Write(this.ToString(), client.getStatistics().toString());
                    }
                }
                finally
                {
                    os.Close();
                }
            }
            catch (Exception ex)
            {
                Log.Write(this.ToString(), "RunReceive", ex);
            }
        }
예제 #8
0
            public void Run()
            {
                try
                {
                    FlashLogger.Info("Handling request from " + socket.GetSession().Destination);
                    UDTInputStream  intStream = socket.GetInputStream();
                    UDTOutputStream outStream = socket.GetOutputStream();
                    byte[]          readBuf   = new byte[32768];

                    //read file name info
                    while (intStream.Read(readBuf) == 0)
                    {
                        Thread.Sleep(100);
                    }

                    //how many bytes to read for the file name
                    byte[] len = new byte[4];
                    //bb.get(len);

                    Array.Copy(readBuf, 0, len, 0, 4);//文件名称长度
                    if (verbose)
                    {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < len.Length; i++)
                        {
                            sb.Append((len[i]).ToString());
                            sb.Append(" ");
                        }
                        Console.WriteLine("[SendFile] name length data: " + sb.ToString());
                    }
                    long length = Decode(len, 0);
                    if (verbose)
                    {
                        Console.WriteLine("[SendFile] name length     : " + length);
                    }
                    byte[] fileName = new byte[(int)length];
                    //读取文件名称
                    Array.Copy(readBuf, 4, fileName, 0, fileName.Length);
                    FileInfo file = new FileInfo(Encoding.UTF8.GetString(fileName));//兼容java
                    Console.WriteLine("[SendFile] File requested: '" + file.FullName + "'");

                    FileStream fis = null;
                    try
                    {
                        long size = file.Length;
                        Console.WriteLine("[SendFile] File size: " + size);
                        //send size info
                        outStream.Write(Encode64(size)); //先写入大小
                        outStream.Flush();               //传输完成

                        long start = DateTime.Now.Ticks;
                        fis = new FileStream(file.FullName, FileMode.Open);

                        CopyFile(fis, outStream, size, false);
                        Console.WriteLine("[SendFile] Finished sending data.");
                        long end = DateTime.Now.Ticks;
                        Console.WriteLine(socket.GetSession().Statistics.toString());
                        double rate = 1000.0 * size / 1024 / 1024 / (end - start);
                        Console.WriteLine("[SendFile] Rate: " + rate.ToString(format) + " MBytes/sec. " + (8 * rate).ToString(format) + " MBit/sec.");
                    }
                    finally
                    {
                        socket.GetSender().Stop();
                        if (fis != null)
                        {
                            fis.Close();
                        }
                    }
                    FlashLogger.Info("Finished request from " + socket.GetSession().Destination);
                }
                catch (Exception ex)
                {
                    FlashLogger.Error(ex.Message);
                }
            }
예제 #9
0
        public void Run()
        {
            Configure();
            verbose = true;
            try{
                UDTReceiver.connectionExpiryDisabled = true;

                UDTClient client = new UDTClient(localPort, localIP);
                client.Connect(this.serverHost, this.serverPort);
                UDTInputStream  inStream  = client.GetInputStream();
                UDTOutputStream outStream = client.GetOutputStream();
                Console.WriteLine("[ReceiveFile] Requesting file " + remoteFile);
                byte[] fName = Encoding.UTF8.GetBytes(remoteFile);//兼容java
                //send file name info
                byte[] nameinfo = new byte[fName.Length + 4];
                Array.Copy(Encode(fName.Length), 0, nameinfo, 0, 4);
                Array.Copy(fName, 0, nameinfo, 4, fName.Length);
                outStream.Write(nameinfo);
                outStream.Flush();
                //pause the sender to save some CPU time
                outStream.PauseOutput();

                //read size info (an 64 bit number)
                byte[] sizeInfo = new byte[8];

                int total = 0;
                while (total < sizeInfo.Length)
                {
                    int r = inStream.Read(sizeInfo);
                    if (r < 0)
                    {
                        break;
                    }
                    total += r;
                }
                //读取文件长度
                long size = Decode(sizeInfo, 0);

                FileInfo file = new FileInfo(localFile);
                Console.WriteLine("[ReceiveFile] Write to local file <" + file.FullName + ">");
                FileStream fos = new FileStream(file.FullName, FileMode.Append);     //准备写入文件

                try{
                    Console.WriteLine("[ReceiveFile] Reading <" + size + "> bytes.");
                    long start = DateTime.Now.Ticks;
                    //and read the file data
                    //Util.copy(in, os, size, false);
                    CopyFile(fos, inStream, size, false);
                    long   end  = DateTime.Now.Ticks;
                    double rate = 1000.0 * size / 1024 / 1024 / (end - start);
                    Console.WriteLine("[ReceiveFile] Rate: " + rate.ToString(format) + " MBytes/sec. "
                                      + (8 * rate).ToString(format) + " MBit/sec.");

                    client.Shutdown();

                    if (verbose)
                    {
                        Console.WriteLine(client.GetStatistics());
                    }
                }finally{
                    fos.Close();
                }
            }catch (Exception ex) {
                //throw new RuntimeException(ex);
            }
        }