BeginWrite() public method

public BeginWrite ( byte array, int offset, int numBytes, AsyncCallback callback, object state ) : IAsyncResult
array byte
offset int
numBytes int
callback AsyncCallback
state object
return IAsyncResult
Example #1
0
 public static void ApplyIPSPatch(string romname, string patchname)
 {
     // Noobish Noobsicle wrote this IPS patching code
     // romname is the original ROM, patchname is the patch to apply
     FileStream romstream = new FileStream(romname, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
     FileStream ipsstream = new FileStream(patchname, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
     int lint = (int)ipsstream.Length;
     byte[] ipsbyte = new byte[ipsstream.Length];
     byte[] rombyte = new byte[romstream.Length];
     IAsyncResult romresult;
     IAsyncResult ipsresult = ipsstream.BeginRead(ipsbyte, 0, lint, null, null);
     ipsstream.EndRead(ipsresult);
     int ipson = 5;
     int totalrepeats = 0;
     int offset = 0;
     bool keepgoing = true;
     while (keepgoing == true)
     {
         offset = ipsbyte[ipson] * 0x10000 + ipsbyte[ipson + 1] * 0x100 + ipsbyte[ipson + 2];
         ipson++;
         ipson++;
         ipson++;
         if (ipsbyte[ipson] * 256 + ipsbyte[ipson + 1] == 0)
         {
             ipson++;
             ipson++;
             totalrepeats = ipsbyte[ipson] * 256 + ipsbyte[ipson + 1];
             ipson++;
             ipson++;
             byte[] repeatbyte = new byte[totalrepeats];
             for (int ontime = 0; ontime < totalrepeats; ontime++)
                 repeatbyte[ontime] = ipsbyte[ipson];
             romstream.Seek(offset, SeekOrigin.Begin);
             romresult = romstream.BeginWrite(repeatbyte, 0, totalrepeats, null, null);
             romstream.EndWrite(romresult);
             ipson++;
         }
         else
         {
             totalrepeats = ipsbyte[ipson] * 256 + ipsbyte[ipson + 1];
             ipson++;
             ipson++;
             romstream.Seek(offset, SeekOrigin.Begin);
             romresult = romstream.BeginWrite(ipsbyte, ipson, totalrepeats, null, null);
             romstream.EndWrite(romresult);
             ipson = ipson + totalrepeats;
         }
         if (ipsbyte[ipson] == 69 && ipsbyte[ipson + 1] == 79 && ipsbyte[ipson + 2] == 70)
             keepgoing = false;
     }
     romstream.Close();
     ipsstream.Close();
 }
Example #2
0
 /// <summary>
 /// Demonstrates the use of the APM with files, through the FileStream class.
 /// This method performs asynchronous reads and writes to copy data from an input
 /// file to an output file.  Reads and writes are interlaced, and proceed in chunks
 /// of 8KB at a time (displaying progress to the console).
 /// </summary>
 static void APMWithFiles()
 {
     FileStream reader = new FileStream("sample.txt", FileMode.Open);
     FileStream writer = new FileStream("sample2.txt", FileMode.Create);
     byte[] buffer1 = new byte[8192], buffer2 = new byte[8192];
     IAsyncResult ar1, ar2 = null;
     while (true)
     {
         ar1 = reader.BeginRead(buffer1, 0, buffer1.Length, null, null);
         while (!ar1.IsCompleted)
         {
             Console.Write("R");
         }
         if (ar2 != null)
         {
             while (!ar2.IsCompleted)
             {
                 Console.Write("W");
             }
         }
         int bytesRead;
         if ((bytesRead = reader.EndRead(ar1)) == 0)
             break;  //No more data to read
         if (ar2 != null)
         {
             writer.EndWrite(ar2);
         }
         Array.Copy(buffer1, buffer2, bytesRead);
         ar2 = writer.BeginWrite(buffer2, 0, bytesRead, null, null);
     }
     Console.WriteLine();
     Console.WriteLine();
 }
        public IAsyncResult BeginProcessRequest (HttpContext context, AsyncCallback cb, object extraData) {

            HttpRequest request = context.Request;
            HttpResponse response = context.Response;
            StringBuilder builder = new StringBuilder();

            response.RedirectLocation = request.QueryString["uri"];
            response.StatusCode = 303;

            builder.AppendFormat("<request time='{0}' filePath='{1}'>", DateTime.Now, request.FilePath);

            IEnumerator enumerator = request.Headers.GetEnumerator();
            for (int i = 0; enumerator.MoveNext(); i++) {
                string name = request.Headers.AllKeys[i].ToString();
                builder.AppendFormat("<{0}>:{1}</{0}>", name, HttpUtility.HtmlEncode(request.Headers[name]));
            }

            builder.Append("</request>\r\n");

            byte[] output = Encoding.ASCII.GetBytes(builder.ToString());
            lock (m_lock) {
                m_file = new FileStream(request.MapPath("~/App_Data/TrackerLog.xml"), FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write, 1024, true);
                m_file.Seek(m_position, SeekOrigin.Begin);
                m_position += output.Length;
                return m_file.BeginWrite(output, 0, output.Length, cb, extraData);
            }
        }
Example #4
0
 public void BeginWriteThrowsForNegativeNumBytes()
 {
     using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
     {
         Assert.Throws<ArgumentOutOfRangeException>("numBytes", () => fs.BeginWrite(new byte[0], 0, -1, null, null));
     }
 }
Example #5
0
 public void BeginWriteThrowsForBadOffset(int arraySize, int offset, int numBytes)
 {
     using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
     {
         Assert.Throws<ArgumentException>(() => fs.BeginWrite(new byte[arraySize], offset, numBytes, null, null));
     }
 }
Example #6
0
 private void WriteLog(LogLevel level, string log)
 {
     var path = string.Format(@"{0}{1}\{2}", YFK.Core.Configuration.YFKConfig.Instance.WebSetting.LogPath, DateTime.Now.ToString("yyyy年MM月dd日"), level.ToString());
     if (path.Contains(":\\") == false)
     {
         if (System.Web.HttpContext.Current != null)
             path = System.Web.HttpContext.Current.Server.MapPath(path);
         else
             path = AppDomain.CurrentDomain.BaseDirectory + path;
     }
     var fileName = string.Format("{0}.txt", DateTime.Now.ToString("HH"));
     if (!Directory.Exists(path))
         Directory.CreateDirectory(path);
     using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Append, FileAccess.Write,
                                           FileShare.Write, 1024, FileOptions.Asynchronous))
     {
         log = string.Format("================记录时间:{0}================\r\n{1}\r\n",
             DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), log);
         byte[] buffer = System.Text.Encoding.UTF8.GetBytes(log + "\r\n");
         IAsyncResult writeResult = fs.BeginWrite(buffer, 0, buffer.Length,
             (asyncResult) =>
             {
                 var fStream = (FileStream)asyncResult.AsyncState;
                 fStream.EndWrite(asyncResult);
             },
             fs);
         fs.Close();
     }
 }
Example #7
0
 public void BeginWriteThrowsForNullArray()
 {
     using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
     {
         Assert.Throws<ArgumentNullException>("array", () => fs.BeginWrite(null, 0, 0, null, null));
     }
 }
        IAsyncResult BeginPreRequestHandlerExecute (Object source, EventArgs e, AsyncCallback cb, Object state) {
            System.Web.HttpApplication app = (System.Web.HttpApplication)source;
            DateTime time = DateTime.Now;

            string line = String.Format(
                "{0,10:d}    {1,11:T}    {2, 32}   {3}\r\n",
                time, time,
                app.User.Identity.IsAuthenticated ?
                app.User.Identity.Name :
                app.Request.UserHostAddress,
                app.Request.Url);

            byte[] output = Encoding.ASCII.GetBytes(line);

            lock (_lock) {
                _file = new FileStream(
                    HttpContext.Current.Server.MapPath("~/App_Data/RequestLog.txt"),
                    FileMode.OpenOrCreate, FileAccess.Write,
                    FileShare.Write, 1024, true);

                _file.Seek(_position, SeekOrigin.Begin);
                _position += output.Length;
                return _file.BeginWrite(output, 0, output.Length, cb, state);
            }
        }
        public FileAsync()
        {
            FileStream fs = new System.IO.FileStream ("test.txt",
                FileMode.Create, FileAccess.Write);

            fs.BeginWrite (new byte[10], 0, 0, FileWriteCallback, fs);

            // Hacemos mas acciones
        }
        public AsyncFileStream()
        {
            Console.WriteLine("Main Thread started. ThreadID = {0}", Thread.CurrentThread.GetHashCode());
             FileStream stream = new FileStream("logfile.txt", FileMode.Append, FileAccess.Write, FileShare.None, 4096, true);
             string msg = "This is a Test";
             byte[] buffer = Encoding.ASCII.GetBytes(msg);

             stream.BeginWrite(buffer, 0, buffer.Length, WriteDone, stream);
        }
Example #11
0
        public void BeginWriteThrowsForClosed()
        {
            FileStream fs;
            using (fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
            {
            }

            Assert.Throws<ObjectDisposedException>(() => fs.BeginWrite(new byte[0], 0, 0, null, null));
        }
 private static void WriteContent(string file, string content)
 {
     var fileStream = new FileStream(file, FileMode.Truncate);
     var state = new FileState
     {
         FileStream = fileStream
     };
     var data = Encoding.ASCII.GetBytes(content);
     fileStream.BeginWrite(data, 0, data.Length, WriteDone, state);
 }
Example #13
0
        public void BeginWriteThrowsForReadOnly()
        {
            string testPath = GetTestFilePath();
            using (FileStream fs = new FileStream(testPath, FileMode.Create, FileAccess.Write))
            {
            }

            using (FileStream fs = new FileStream(testPath, FileMode.Open, FileAccess.Read))
            {
                Assert.Throws<NotSupportedException>(() => fs.BeginWrite(new byte[0], 0, 0, null, null));
            }
        }
Example #14
0
 public static string SaveFile(string name, byte[] bs)
 {
     int rtn = -1;
     try
     {
         string path = paths[ch.GetPrimary(name)]  + name;
         Log.Write("保存文件路径:" + path);
         FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Delete | FileShare.ReadWrite, 8192, FileOptions.WriteThrough | FileOptions.Asynchronous);
         IAsyncResult ir = fs.BeginWrite(bs, 0, bs.Length, WriteCallback, fs);
     }
     catch (Exception e)
     {
         Log.Error("FileHelper.SaveFile:" + e.Message);
     }
     return name;
 }
        public void СохранитьФайл(string Проект, string Каталог, string Файл, string Содержание)
        {
            Interlocked.Increment(ref КоличествоФайловВсего);
            var ИмяФайла = ПолучитьИПроверитьДиректорию(Проект, Каталог) + "\\" + Файл;
            var Кодировка = ВыборКодировки(Файл);
            var Сигнатура = Кодировка.GetPreamble();
            Содержание = ЗаменитьТокены(Содержание);

            var НовыйПоток = СложитьДваПотока(Сигнатура,Кодировка.GetBytes(Содержание));

            var СтарыйПоток = new byte[0];
            if (File.Exists(ИмяФайла))
            {
                СтарыйПоток = File.ReadAllBytes(ИмяФайла);
            }
            var ЗаписыватьФайл = НовыйПоток.Length != СтарыйПоток.Length;
            if (!ЗаписыватьФайл)
            {
                ЗаписыватьФайл = !CRC.ПотокиИдентичны(НовыйПоток, СтарыйПоток);
            }
            //ЗаписыватьФайл = true;
            if (!ЗаписыватьФайл)
            {
                return;
            }
            Interlocked.Increment(ref КоличествоФайловКЗаписи);
            //File.WriteAllBytes(ИмяФайла, НовыйПоток);
            //Interlocked.Increment(ref КоличествоФайловЗаписано);
            ИзменитьАтрибутЧтенияФайла(ИмяФайла, false);
            try
            {
                using (var ПотокФайла = new FileStream(ИмяФайла, FileMode.Create, FileAccess.Write, FileShare.Write, 4096, true))
                {
                    var МаркерВызова = ПотокФайла.BeginWrite(НовыйПоток, 0, НовыйПоток.Length, ОбратныйВызовСохраненияФайла, ИмяФайла);
                    Ожидания.Add(МаркерВызова.AsyncWaitHandle);
                }
            }
            catch (Exception Исключение)
            {
                if (Interlocked.Increment(ref КоличествоОшибокЗаписи) < 10)
                {
                    var Сообщение = ((Исключение.InnerException == null)? Исключение.Message: Исключение.InnerException.Message);
                    Console.WriteLine(Сообщение);
                }
            }
        }
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) {

            HttpRequest request = context.Request;
            m_response = context.Response;
            m_response.ContentType = "text/xml";

            NameValueCollection form = request.Form;

            string name = form.Get("name");
            string slug = form.Get("slug");
            string base_uri = form.Get("base_uri");
            string base_path = form.Get("base_path");
            string title = form.Get("title");
            string ip = context.Request.UserHostAddress.ToString();

            Entry entry = new Entry { Published = DateTime.Now, Updated = DateTime.Now, Title = title };

            using (MemoryStream stream = new MemoryStream()) {

                m_xSerializer.Serialize(stream, (Entry)entry);
                stream.Seek(0, 0);

                byte[] output = stream.GetBuffer();
                char[] chars = m_encoding.GetChars(output, 0, output.Length);

                using (XmlReader reader = XmlReader.Create(stream)) {
                    using (StreamWriter sWriter = new StreamWriter(m_response.OutputStream, Encoding.UTF8)) {
                        while (reader.Read()) {
                            sWriter.Write(reader.ReadOuterXml());
                        }
                    }
                }

                lock (m_lock) {
                    string basePath = request.MapPath(String.Format("~{0}", base_path));
                    Console.WriteLine(basePath);
                    if (!Directory.Exists(basePath)) {
                        Directory.CreateDirectory(basePath);
                    }
                    m_file = new FileStream(String.Format("{0}/{1}.xml", basePath, Guid.NewGuid()), FileMode.Create, FileAccess.Write, FileShare.ReadWrite, 1024, true);
                    m_file.Seek(0, 0);
                    return m_file.BeginWrite(output, 0, output.Length, cb, extraData);
                }
            }
        }
Example #17
0
        public static void CopyFile(String sourcePath, String destinationPath, Action<String, String, Exception> completed)
        {
            Stream source = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
            Stream destination = new FileStream(destinationPath, FileMode.Create, FileAccess.Write);
            byte[] buffer = new byte[0x1000];
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(null);

            Action<Exception> cbCompleted = e =>
            {
                if (completed != null) asyncOp.Post(delegate
                     {
                         source.Close();
                         destination.Close();
                         completed(sourcePath, destinationPath, e);
                     }, null);
            };

            AsyncCallback rc = null;
            rc = readResult =>
            {
                try
                {
                    int read = source.EndRead(readResult);
                    if (read > 0)
                    {
                        destination.BeginWrite(buffer, 0, read, writeResult =>
                        {
                            try
                            {
                                destination.EndWrite(writeResult);
                                source.BeginRead(
                                    buffer, 0, buffer.Length, rc, null);
                            }
                            catch (Exception exc) { cbCompleted(exc); }
                        }, null);
                    }
                    else cbCompleted(null);
                }
                catch (Exception exc) { cbCompleted(exc); }
            };

            source.BeginRead(buffer, 0, buffer.Length, rc, null);
        }
        public override void ShowUsage()
        {
            //需要在 FileStream 异步调用 I/O线程,必须使用以下构造函数建立 FileStream 对象,并把useAsync设置为 true。
            //FileStream stream = new FileStream ( string path, FileMode mode, FileAccess access, FileShare share, int bufferSize,bool useAsync ) ;
            //其中 path 是文件的相对路径或绝对路径; mode 确定如何打开或创建文件; access 确定访问文件的方式; share 确定文件如何进程共享; bufferSize 是代表缓冲区大小,一般默认最小值为8,在启动异步读取或写入时,文件大小一般大于缓冲大小; userAsync代表是否启动异步I/O线程。
            ThreadPool.SetMaxThreads(1000, 1000);
            ThreadPoolMessage("Start");

            string filePath = AppDomain.CurrentDomain.BaseDirectory + "Demo.txt";
            FileStream stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, 1024, true);
            byte[] bytes = new byte[16384];
            string message = "An operating-system ThreadId has no fixed relationship........";
            bytes = Encoding.Unicode.GetBytes(message);
            //启动异步写入
            stream.BeginWrite(bytes, 0, (int)bytes.Length, new AsyncCallback(Callback), stream);
            stream.Flush();
            Console.WriteLine("注意:如果你看到的测试结果正好相反:工作者线程为999,I/O线程为1000,这是因为FileStream的文件容量小于缓冲值1024所致的。此时文件将会一次性读取或写入,而系统将启动工作者线程而非I/O线程来处理回调函数。");
            Console.ReadKey();
        }
		public async void TestAsyncPLINQ()
		{
			using (var ms = new MemoryStream())
			{
				Enumerable.Range(0, 1000000)
					.AsParallel()
					.Select(i => new { num = i, val = Math.Sin(i) })
					.Where(elem => elem.val > 0)
					.OrderBy(elem => elem.val)
					.ForAll(elem => 
						{
							var buf = Encoding.GetEncoding(1251).GetBytes(elem.num + "\t" + elem.val + "\r\n");
							lock(ms)
								ms.Write(buf, 0, buf.Length);
						});

				var semaphore = new Semaphore(0,1);
				using (FileStream fStream = new FileStream("sins.txt", FileMode.Create,
					FileAccess.ReadWrite, FileShare.None, 4096, true))
				{
					Console.WriteLine("File was {0}opened asynchronously", fStream.IsAsync ? "" : "NOT ");

					fStream.BeginWrite(ms.GetBuffer(), 0, (int)ms.Position,
						asyncResult =>
						{
							var fs = (FileStream)asyncResult.AsyncState;
							fs.EndWrite(asyncResult);
							Console.WriteLine("Done with I/O!");
							semaphore.Release();
						}, fStream);
					Console.WriteLine("Free for work! But nothing to do...");
					semaphore.WaitOne();

//					ms.Position = 0;
//					var copyToAsyncTask = ms.CopyToAsync(fStream);
//					Console.WriteLine("Free for work! But nothing to do...");
//					await copyToAsyncTask;
//					Console.WriteLine("Done with I/O!");
				}
			}
		}
        public static void WorkItemMethod(object mainEvent)
        {
            Console.WriteLine("\nStarting WorkItem.\n");
            AutoResetEvent autoEvent = new AutoResetEvent(false);

            // Create some data.
            const int ArraySize = 10000;
            const int BufferSize = 1000;
            byte[] byteArray = new Byte[ArraySize];
            new Random().NextBytes(byteArray);

            // Create two files and two State objects.
            FileStream fileWriter1 =
                new FileStream(@"C:\democode\[email protected]##.dat", FileMode.Create,
                FileAccess.ReadWrite, FileShare.ReadWrite,
                BufferSize, true);
            FileStream fileWriter2 =
                new FileStream(@"C:\democode\[email protected]##.dat", FileMode.Create,
                FileAccess.ReadWrite, FileShare.ReadWrite,
                BufferSize, true);
            State stateInfo1 = new State(fileWriter1, autoEvent);
            State stateInfo2 = new State(fileWriter2, autoEvent);

            // Asynchronously write to the files.
            fileWriter1.BeginWrite(byteArray, 0, byteArray.Length,
                new AsyncCallback(EndWriteCallback), stateInfo1);
            fileWriter2.BeginWrite(byteArray, 0, byteArray.Length,
                new AsyncCallback(EndWriteCallback), stateInfo2);

            // Wait for the callbacks to signal.
            autoEvent.WaitOne();
            autoEvent.WaitOne();

            fileWriter1.Close();
            fileWriter2.Close();
            Console.WriteLine("\nEnding WorkItem.\n");

            // Signal Main that the work item is finished.
            ((AutoResetEvent)mainEvent).Set();
        }
Example #21
0
 static void Main(string[] args)
 {
     int max = 5000000;
     Stopwatch sw = Stopwatch.StartNew();
     Console.WriteLine(sw.Elapsed + " start calculating sinuses");
     var sins = string.Join("\r\n",
         Enumerable.Range(0, max)
         .AsParallel()
         .Select(x => new {x, sinX=Math.Sin(x)})
         .Where(pair => pair.sinX > 0)
         .OrderBy(pair => pair.sinX)
         .Select(pair => pair.ToString()));
     byte[] data = Encoding.ASCII.GetBytes(sins);
     Console.WriteLine(sw.Elapsed + " start writing sinuses");
     var fs = new FileStream("sins.txt",
         FileMode.Create, FileAccess.Write, FileShare.None, 4096,
         FileOptions.WriteThrough
         | FileOptions.Asynchronous
         );
     //            fs.Write(data, 0, data.Length);
     //            Console.WriteLine(sw.Elapsed + " sinuses written!");
     fs.BeginWrite(data, 0, data.Length, res =>
     {
         Console.WriteLine(sw.Elapsed + " sinuses written!");
         fs.EndWrite(res);
         fs.Dispose();
         data = null;
     }, null);
     //            Console.WriteLine(sw.Elapsed + " start calculating cosinuses");
     //            var coses = Enumerable.Range(0, max)
     //                .AsParallel()
     //                .Select(x => new { x, cosX = Math.Cos(x) })
     //                .Where(pair => pair.cosX > 0)
     //                .OrderBy(pair => pair.cosX)
     //                .Select(pair => pair.ToString());
     //            Console.WriteLine(sw.Elapsed + " start writing cosinuses");
     //            var cosinuses = string.Join("\r\n", coses);
     //            File.WriteAllText("cosinuses.txt", cosinuses);
     //            Console.WriteLine(sw.Elapsed);
 }
		public void BeginWrite_Disposed () 
		{
			string path = TempFolder + Path.DirectorySeparatorChar + "temp";
			DeleteFile (path);
			FileStream stream = new FileStream (path, FileMode.OpenOrCreate, FileAccess.Write);
			stream.Close ();
			stream.EndWrite (stream.BeginWrite (new byte[8], 0, 8, null, null));
		}
Example #23
0
        static void Main(string[] args)
        {
            const string UsermodeDeviceSpace = "\\\\.\\Global\\";
            string devGuid = GetDeviceGuid();
            Console.WriteLine(HumanName(devGuid));
            IntPtr ptr = CreateFile(UsermodeDeviceSpace + devGuid + ".tap", FileAccess.ReadWrite,
                FileShare.ReadWrite, 0, FileMode.Open, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, IntPtr.Zero);
            int len;
            IntPtr pstatus = Marshal.AllocHGlobal(4);
            Marshal.WriteInt32(pstatus, 1);
            DeviceIoControl(ptr, TAP_CONTROL_CODE(6, METHOD_BUFFERED) /* TAP_IOCTL_SET_MEDIA_STATUS */, pstatus, 4,
                    pstatus, 4, out len, IntPtr.Zero);
            IntPtr ptun = Marshal.AllocHGlobal(12);
            Marshal.WriteInt32(ptun, 0, 0x0100030a);
            Marshal.WriteInt32(ptun, 4, 0x0000030a);
            Marshal.WriteInt32(ptun, 8, unchecked((int)0x00ffffff));
            DeviceIoControl(ptr, TAP_CONTROL_CODE(10, METHOD_BUFFERED) /* TAP_IOCTL_CONFIG_TUN */, ptun, 12,
                ptun, 12, out len, IntPtr.Zero);
            Tap = new FileStream(ptr, FileAccess.ReadWrite, true, 10000, true);
            byte[] buf = new byte[10000];
            object state = new int();
            WaitObject = new EventWaitHandle(false, EventResetMode.AutoReset);
            object state2 = new int();
            WaitObject2 = new EventWaitHandle(false, EventResetMode.AutoReset);
            AsyncCallback readCallback = new
                AsyncCallback(ReadDataCallback);
            AsyncCallback writeCallback = new
                AsyncCallback(WriteDataCallback);
            IAsyncResult res, res2;

            // FIXME: for now we hardcode the ip address and port
            //string serverIP = "188.26.227.131";
            //int port = 9999;
            // Create a UDP socket to connect to the main server
            //UdpClient udpClient = new UdpClient(port);

            try
            {
                //udpClient.Connect(serverIP, port);

                while (true)
                {
                    res = Tap.BeginRead(buf, 0, 10000, readCallback, state);
                    WaitObject.WaitOne();
                    //
                    // Reverse IPv4 addresses and send back to tun
                    //
                    for (int i = 0; i < 4; ++i)
                    {
                        byte tmp = buf[12 + i]; buf[12 + i] = buf[16 + i]; buf[16 + i] = tmp;
                    }
                    res2 = Tap.BeginWrite(buf, 0, BytesRead, writeCallback, state2);
                    WaitObject2.WaitOne();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Example #24
0
        private void SaveGoods(bool forced = false)
        {
            if (!Directory.Exists(Settings.GoodsPath)) Directory.CreateDirectory(Settings.GoodsPath);

            for (int i = 0; i < MapList.Count; i++)
            {
                Map map = MapList[i];

                if (map.NPCs.Count < 1) continue;

                for (int j = 0; j < map.NPCs.Count; j++)
                {
                    NPCObject npc = map.NPCs[j];

                    if (forced)
                    {
                        npc.ProcessGoods(forced);
                    }

                    if (!npc.NeedSave) continue;

                    string path = Settings.GoodsPath + npc.Info.Index.ToString() + ".msdn";

                    MemoryStream mStream = new MemoryStream();
                    BinaryWriter writer = new BinaryWriter(mStream);
                    int Temp = 9999;
                    writer.Write(Temp);
                    writer.Write(Version);
                    writer.Write(CustomVersion);
                    writer.Write(npc.UsedGoods.Count);

                    for (int k = 0; k < npc.UsedGoods.Count; k++)
                    {
                        npc.UsedGoods[k].Save(writer);
                    }

                    FileStream fStream = new FileStream(path, FileMode.Create);
                    byte[] data = mStream.ToArray();
                    fStream.BeginWrite(data, 0, data.Length, EndSaveGoodsAsync, fStream);
                }
            }
        }
Example #25
0
 private void SaveGuilds(bool forced = false)
 {
     if (!Directory.Exists(Settings.GuildPath)) Directory.CreateDirectory(Settings.GuildPath);
     for (int i = 0; i < GuildList.Count; i++)
     {
         if (GuildList[i].NeedSave || forced)
         {
             GuildList[i].NeedSave = false;
             MemoryStream mStream = new MemoryStream();
             BinaryWriter writer = new BinaryWriter(mStream);
             GuildList[i].Save(writer);
             FileStream fStream = new FileStream(Settings.GuildPath + i.ToString() + ".mgdn", FileMode.Create);
             byte[] data = mStream.ToArray();
             fStream.BeginWrite(data, 0, data.Length, EndSaveGuildsAsync, fStream);
         }
     }
 }
Example #26
0
        private void BeginSaveAccounts()
        {
            if (Saving) return;

            Saving = true;

            using (MemoryStream mStream = new MemoryStream())
            {
                if (File.Exists(AccountPath))
                {
                    if (!Directory.Exists(BackUpPath)) Directory.CreateDirectory(BackUpPath);
                    string fileName = string.Format("Accounts {0:0000}-{1:00}-{2:00} {3:00}-{4:00}-{5:00}.bak", Now.Year, Now.Month, Now.Day, Now.Hour, Now.Minute, Now.Second);
                    if (File.Exists(Path.Combine(BackUpPath, fileName))) File.Delete(Path.Combine(BackUpPath, fileName));
                    File.Move(AccountPath, Path.Combine(BackUpPath, fileName));
                }

                SaveAccounts(mStream);
                FileStream fStream = new FileStream(AccountPath + "n", FileMode.Create);

                byte[] data = mStream.ToArray();
                fStream.BeginWrite(data, 0, data.Length, EndSaveAccounts, fStream);
            }
        }
Example #27
0
        void _subscriber_OnReceiveMessageEventHandler(object obj)
        {
            if (obj == null)
            {
                AddToTextBox("收到为空的信息");
                return;
            }
            if (obj is string)
            {
                AddToTextBox(obj.ToString());
            }
            else if (obj is DateTime)
            {
                AddToTextBox(((DateTime)obj).ToString(CultureInfo.InvariantCulture));
            }
            else
            {
                if (obj is byte[])
                {
                    string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                      string.Format("{0}.jpg", DateTime.Now.ToString("yyyy_MM-dd_hh_mm_ss")));
                    FileStream writer = new FileStream(fileName, FileMode.OpenOrCreate);

                    byte[] buffer = (byte[])(obj);
                    writer.BeginWrite(buffer, 0, buffer.Length, delegate(IAsyncResult result)
                            {
                                writer.EndWrite(result);
                                InvokeTextBox(this.sendInfoRtb, string.Format("接收文件读写完成,共{0}", buffer.Length));
                                writer.Close();
                            }, null);

                    this.AddToTextBox(string.Format("接受到文件"));
                }

            }
        }
Example #28
0
        private static void WriteFileContent(string message, string location)
        {
            FileStream fStream = new FileStream(location, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, true);
            byte[] bytes = ASCIIEncoding.ASCII.GetBytes(Environment.NewLine + message);

            IAsyncResult asyncResult = fStream.BeginWrite(
                bytes, 0, bytes.Length,
                new AsyncCallback(WriteCallback),
                fStream);
        }
Example #29
0
		private IEnumerator DownloadCoroutine()
		{
			WWW www = null;
			string ext = Path.GetExtension(url);
            if (ext.Contains("?"))
                ext = ext.Substring(0, ext.IndexOf('?'));
#if !UNITY_WEBPLAYER
            if (cached && File.Exists(Application.temporaryCachePath + "/" + this.guid + ext))
            {
                www = new WWW("file:///" + Application.temporaryCachePath + "/" + this.guid + ext);
#if DEBUG_LOG
                Debug.Log("DEBUG: TileDownloader.DownloadCoroutine: loading tile from cache: url: " + www.url);
#endif
            }
            else
#endif
            {
                www = new WWW(url);
#if DEBUG_LOG
                Debug.Log("DEBUG: TileDownloader.DownloadCoroutine: loading tile from provider: url: " + www.url
#if !UNITY_WEBPLAYER
                    + "(cached: " + cached + ")"
#endif
                    );
#endif
            }

            yield return www;
			
#if DEBUG_PROFILE
			UnitySlippyMap.Profiler.Begin("TileDownloader.TileEntry.DownloadCoroutine");
#endif

#if DEBUG_PROFILE
			UnitySlippyMap.Profiler.Begin("www error test");
#endif
			if (www.error == null && www.text.Contains("404 Not Found") == false)
			{
#if DEBUG_PROFILE
				UnitySlippyMap.Profiler.End("www error test");
#endif
#if DEBUG_PROFILE
				UnitySlippyMap.Profiler.Begin("www.texture");
#endif

                Texture2D texture = new Texture2D(1, 1, TextureFormat.ARGB32, true);
				www.LoadImageIntoTexture(texture);
				
#if DEBUG_PROFILE
				UnitySlippyMap.Profiler.End("www.texture");
#endif

#if DEBUG_PROFILE
				UnitySlippyMap.Profiler.Begin("is cached?");
#endif
#if !UNITY_WEBPLAYER
                if (this.cached == false)
				{
#if DEBUG_PROFILE
					UnitySlippyMap.Profiler.End("is cached?");
#endif
    					
#if DEBUG_PROFILE
					UnitySlippyMap.Profiler.Begin("set TileEntry members");
#endif

	                byte[] bytes = www.bytes;
					
					this.size = bytes.Length;
					this.guid = Guid.NewGuid().ToString();
#if DEBUG_PROFILE
					UnitySlippyMap.Profiler.End("set TileEntry members");
#endif
					
#if DEBUG_PROFILE
					UnitySlippyMap.Profiler.Begin("new FileStream & FileStream.BeginWrite");
#endif
					FileStream fs = new FileStream(Application.temporaryCachePath + "/" + this.guid + ext, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true);
					fs.BeginWrite(bytes, 0, bytes.Length, new AsyncCallback(EndWriteCallback), new AsyncInfo(this, fs));
#if DEBUG_PROFILE
					UnitySlippyMap.Profiler.End("new FileStream & FileStream.BeginWrite");
#endif
				
#if DEBUG_LOG
					Debug.Log("DEBUG: TileEntry.DownloadCoroutine: done loading: " + www.url + ", writing to cache: " + fs.Name);
#endif
				}
				else
				{
#if DEBUG_PROFILE
					UnitySlippyMap.Profiler.End("is cached?");
#endif
#if DEBUG_LOG
	    			Debug.Log("DEBUG: TileEntry.DownloadCoroutine: done loading from cache: " + www.url + " [" + url + "]");
#endif
				}

				this.timestamp = (DateTime.Now - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
#endif

#if DEBUG_PROFILE
				UnitySlippyMap.Profiler.Begin("Tile.SetTexture");
#endif
				tile.SetTexture(texture);
#if DEBUG_PROFILE
				UnitySlippyMap.Profiler.End("Tile.SetTexture");
#endif
			}
			else
			{
#if DEBUG_PROFILE
				UnitySlippyMap.Profiler.End("www error test");
#endif
				this.error = true;
#if DEBUG_LOG
				Debug.LogError("ERROR: TileEntry.DownloadCoroutine: done downloading: " + www.url + " with error: " + www.error);
#endif
			}
			
#if DEBUG_PROFILE
			UnitySlippyMap.Profiler.End("TileDownloader.TileEntry.DownloadCoroutine");
#endif
		}
        private void DoSequentialWrite(
            BlobTransferContext transferContext,
            FileStream stream)
        {
            if (transferContext.CancellationToken.IsCancellationRequested)
            {
                return;
            }

            byte[] buffer = null;

            if (transferContext.BlocksForFileIO.TryGetValue(transferContext.NextFileIOBlock, out buffer) && buffer != null)
            {
                transferContext.IsReadingOrWriting = true;
                long endOfRange = transferContext.Length + transferContext.InitialOffset;

                long beginFilePosition = (long)transferContext.NextFileIOBlock * transferContext.BlockSize + transferContext.InitialOffset;
                beginFilePosition = beginFilePosition > endOfRange
                    ? endOfRange
                    : beginFilePosition;

                long nextBeginFilePosition = (transferContext.NextFileIOBlock + 1) * (long)transferContext.BlockSize + transferContext.InitialOffset;
                nextBeginFilePosition = nextBeginFilePosition > endOfRange
                                            ? endOfRange
                                            : nextBeginFilePosition;

                int bytesToWrite = (int)(nextBeginFilePosition - beginFilePosition);

                ApplyEncryptionTransform(transferContext.FileEncryption, transferContext.InitializationVector, beginFilePosition, buffer, bytesToWrite);

                stream.BeginWrite(
                    buffer,
                    0,
                    bytesToWrite,
                    result3 =>
                    {

                        SuccessfulOrRetryableResult wasWriteSuccessful =
                            IsActionSuccessfulOrRetryable(transferContext, () => stream.EndWrite(result3));

                        transferContext.MemoryManager.ReleaseBuffer(buffer);

                        if (!wasWriteSuccessful.IsSuccessful)
                        {
                            transferContext.IsReadingOrWriting = false;
                            return;
                        }

                        transferContext.NextFileIOBlock++;

                        Interlocked.Add(ref transferContext.BytesWrittenOrReadToFile, bytesToWrite);

                        InvokeProgressCallback(transferContext, transferContext.BytesWrittenOrReadToFile, bytesToWrite);

                        transferContext.IsReadingOrWriting = false;

                        if (transferContext.BytesWrittenOrReadToFile >= transferContext.Length)
                        {
                            transferContext.IsComplete = true;
                            transferContext.OnComplete();
                        }
                    },
                    null);
            }
        }