Ejemplo n.º 1
0
        /// <summary>
        /// 文件传输
        /// </summary>
        /// <param name="fis">文件读取流</param>
        /// <param name="outStream">网络传输流</param>
        /// <param name="size">文件大小</param>
        /// <param name="flush">是否及时刷新</param>
        public static void CopyFileSender(FileStream fis, UDTOutputStream outStream, long size, bool flush)
        {
            byte[] buf = new byte[8 * 65536];
            int    c;
            long   read = 0;

            while (true)
            {
                c = fis.Read(buf, 0, buf.Length);
                if (c < 0)
                {
                    break;
                }
                read += c;
                Console.WriteLine("writing <" + c + "> bytes");
                outStream.Write(buf, 0, c);
                if (flush)
                {
                    outStream.Flush();
                }
                if (read >= size && size > -1)
                {
                    break;
                }
            }
            if (!flush)
            {
                outStream.Flush();
            }
        }
Ejemplo n.º 2
0
        private static void copyFile(FileStream file, UDTOutputStream os)
        {
            try
            {
                byte[] filebuf = new byte[file.Length];
                file.Read(filebuf, 0, (int)file.Length);

                //可以读取的长度
                int numBytesToRead = (int)file.Length;
                //已经读取的长度
                int numBytesRead = 0;
                while (true)
                {
                    int len = 0;
                    len = Math.Min(1024 * 1024, numBytesToRead);
                    byte[] buf = new byte[len];
                    Array.Copy(filebuf, numBytesRead, buf, 0, len);
                    os.Write(buf, 0, len);

                    numBytesRead   += len;
                    numBytesToRead -= len;
                    if (numBytesToRead == 0)
                    {
                        break;
                    }
                }
                os.Flush();
                file.Close();
            }
            catch (Exception exc)
            {
                Log.Write("[SendFile] File err", exc);
            }
        }
Ejemplo n.º 3
0
        public void Run()
        {
            try
            {
                //create an UDTServerSocket on a free port
                UDTServerSocket server = new UDTServerSocket(0);
                // do hole punching to allow the client to connect
                IPAddress  clientAddress = IPAddress.Parse(clientIP);
                IPEndPoint point         = new IPEndPoint(clientAddress, clientPort);
                //发送一字节确认端口
                Util.DoHolePunch(server.getEndpoint(), point);
                int localPort = server.getEndpoint().LocalPort; //获取真实端口
                                                                //output client port
                writeToOut("OUT: " + localPort);

                //now start the send...
                UDTSocket       socket    = server.Accept();
                UDTOutputStream outStream = socket.GetOutputStream();
                FileInfo        file      = new FileInfo(localFilename);
                if (!file.Exists)
                {
                    Console.WriteLine("没有文件:" + localFilename);
                    socket.Close();
                    server.ShutDown();
                    return;
                }
                FileStream fis = new FileStream(localFilename, FileMode.Open);
                try
                {
                    //send file size info
                    long size = fis.Length;
                    PacketUtil.Encode(size);
                    outStream.Write(PacketUtil.Encode(size));
                    long start = DateTime.Now.Ticks;
                    //and send the file
                    Util.CopyFileSender(fis, outStream, size, false);
                    long end = DateTime.Now.Ticks;
                    Console.WriteLine(socket.GetSession().Statistics);
                    float mbRate   = 1000 * size / 1024 / 1024 / (end - start);
                    float mbitRate = 8 * mbRate;
                    Console.WriteLine("Rate: " + (int)mbRate + " MBytes/sec. " + mbitRate + " mbit/sec.");
                }
                finally
                {
                    fis.Close();
                    socket.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// copy input data from the source stream to the target stream
        /// 用在发送文件
        /// </summary>
        /// <param name="source">文件流</param>
        /// <param name="target">output stream to write to</param>
        /// <param name="size">要接收的总长度</param>
        /// <param name="flush">每次写入后是否清除此流的缓冲区</param>
        public static void copySend(FileStream source, UDTOutputStream target, long size, bool flush)
        {
            try
            {
                byte[] filebuf = new byte[source.Length];
                source.Read(filebuf, 0, (int)source.Length);

                //可以读取的长度
                int numBytesToRead = (int)source.Length;
                //已经读取的长度
                int numBytesRead = 0;
                target.Write(filebuf, 0, filebuf.Length);
                //while (true)
                //{
                //    int len = 0;
                //    len = Math.Min(512 * 1024, numBytesToRead);
                //    if (len == 0)
                //        break;
                //    byte[] buf = new byte[len];
                //    Array.Copy(filebuf, numBytesRead, buf, 0, len);
                //    //Log.Write("writing <"+len+"> bytes");
                //    target.Write(buf, 0, len);

                //    numBytesRead += len;
                //    numBytesToRead -= len;

                //    if (flush)
                //        target.Flush();
                //    Thread.Sleep(200);
                //}
                //if (!flush)
                //{
                //    target.Flush();
                //}
                source.Close();
            }
            catch (Exception exc)
            {
                source.Close();
                Log.Write("copySend-SendFile", exc);
            }
        }
Ejemplo n.º 5
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);
            }
        }
Ejemplo n.º 6
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);
            }
        }
Ejemplo n.º 7
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);
                }
            }
Ejemplo n.º 8
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);
            }
        }