public void Save(Map mapToSave, string path) { if (mapToSave == null) throw new ArgumentNullException("mapToSave"); if (path == null) throw new ArgumentNullException("path"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } // Write metadata/config file using (StreamWriter sw = File.CreateText(Path.Combine(path, ConfigFileName))) { sw.WriteLine("; Converted by {0} on {1}", Updater.UserAgent, DateTime.Now.ToCompactString()); sw.WriteLine("Size_X = {0}", mapToSave.Width); sw.WriteLine("Size_Y = {0}", mapToSave.Length); sw.WriteLine("Size_Z = {0}", mapToSave.Height); sw.WriteLine("Spawn_X = {0}", FromPositionCoord(mapToSave.Spawn.X)); sw.WriteLine("Spawn_Y = {0}", FromPositionCoord(mapToSave.Spawn.Y)); sw.WriteLine("Spawn_Z = {0}", FromPositionCoord(mapToSave.Spawn.Z)); sw.WriteLine("Spawn_Rot = {0}", FromPositionAngle(mapToSave.Spawn.R)); sw.WriteLine("Spawn_Look = {0}", FromPositionAngle(mapToSave.Spawn.L)); } // Write compressed block data using (FileStream fs = File.Create(Path.Combine(path, DataFileName))) { using (GZipStream gs = new GZipStream(fs, CompressionMode.Compress)) { // Buffering necessary to avoid overhead of writing byte-at-a-time using (BufferedStream bs = new BufferedStream(gs, WriteBufferSize)) { for (int i = 0; i < mapToSave.Volume; i++) { bs.WriteByte(mapToSave.Blocks[i]); bs.WriteByte(0); bs.WriteByte(0xFF); bs.WriteByte(0xFF); } } } } }
public static void Compress(Stream instream, Stream outstream, int blockSize) { BufferedStream inStream = new BufferedStream(outstream); inStream.WriteByte(0x42); inStream.WriteByte(90); BufferedStream stream2 = new BufferedStream(instream); int num = stream2.ReadByte(); BZip2OutputStream stream3 = new BZip2OutputStream(inStream); while (num != -1) { stream3.WriteByte((byte) num); num = stream2.ReadByte(); } stream2.Close(); stream3.Close(); }
/* add a jpeg frame to an AVI file */ public void avi_add(u8[] buf, uint size) { lock (locker) { uint osize = size; Console.WriteLine(DateTime.Now.Millisecond + " avi frame"); db_head db = new db_head { db = "00dc".ToCharArray(), size = size }; fd.Write(StructureToByteArray(db), 0, Marshal.SizeOf(db)); uint offset = (uint)fd.Position; fd.Write(buf, 0, (int)size); indexs.Add(new AVIINDEXENTRY() { ckid = "00dc".ToCharArray(), dwChunkLength = size, dwChunkOffset = (offset - 8212 + 4), dwFlags = 0x10 }); while (fd.Position % 2 != 0) { size++; fd.WriteByte(0); //fd.Seek(1, SeekOrigin.Current); } nframes++; totalsize += size; if (((DateTime.Now - start).TotalSeconds * targetfps) > nframes) { avi_add(buf, osize); Console.WriteLine("Extra frame"); } } }
static void Main(string[] args) { FileStream fs = new FileStream("Hoo.txt", FileMode.Create, FileAccess.ReadWrite); BufferedStream bs = new BufferedStream(fs); Console.WriteLine("Length: {0}\tPosition: {1}", bs.Length, bs.Position); for (int i = 0; i < 64; i++) { bs.WriteByte((byte)i); } Console.WriteLine("Length: {0}\tPosition: {1}", bs.Length, bs.Position); Console.WriteLine("\nContents:"); byte[] ba = new byte[bs.Length]; bs.Position = 0; bs.Read(ba, 0, (int)bs.Length); foreach (byte b in ba) { Console.Write("{0, -3}", b); } string s = "Foo"; for (int i = 0; i < 3; i++) { bs.WriteByte((byte)s[i]); } Console.WriteLine("Length: {0}\tPosition: {1}", bs.Length, bs.Position); for (int i = 0; i < (256-67) + 1; i++) { bs.WriteByte((byte)i); } Console.WriteLine("Length: {0}\tPosition: {1}", bs.Length, bs.Position); bs.Close(); Console.ReadLine(); }
public static void Decompress(Stream instream, Stream outstream) { BufferedStream stream = new BufferedStream(outstream); BufferedStream zStream = new BufferedStream(instream); if ((zStream.ReadByte() == 0x42) && (zStream.ReadByte() == 90)) { BZip2InputStream stream3 = new BZip2InputStream(zStream); for (int i = stream3.ReadByte(); i != -1; i = stream3.ReadByte()) { stream.WriteByte((byte) i); } stream.Flush(); } }
public void Buffered_Stream_buffers_and_forwards_writes_and_flushes_before_close() { var mock = new Mock<Stream>(); Stream stream = mock.Object; mock.SetupGet(d => d.CanRead).Returns(true); mock.SetupGet(d => d.CanWrite).Returns(true); BufferedStream bs = new BufferedStream(stream); bs.WriteByte((byte)'a'); bs.Flush(); bs.Close(); mock.Verify(d => d.Write(It.Is<byte[]>(array => array.Length > 0 && array[0] == 'a'), 0, 1)); mock.Verify(d => d.Flush()); mock.Verify(d => d.Close()); }
private static void runClient(string message) { TcpClient client = new TcpClient("localhost", 8888); NetworkStream netStream = client.GetStream(); using (CryptoStream cryptoStream = new CryptoStream(netStream, new SHA512Managed(), CryptoStreamMode.Write)) { using (GZipStream zipStream = new GZipStream(cryptoStream, CompressionMode.Compress)) { using (BufferedStream buffStream = new BufferedStream(zipStream, 64)) { foreach (var b in Encoding.Unicode.GetBytes(message)) { buffStream.WriteByte(b); } } } } }
static void FileStreamAndBufferedStream() { System.IO.Stream fileStream = System.IO.File.Open("./file.txt", System.IO.FileMode.Open); System.IO.BufferedStream bufferedStream = new System.IO.BufferedStream(fileStream); System.Console.WriteLine("CanRead: " + bufferedStream.CanRead); System.Console.WriteLine("CanWrite: " + bufferedStream.CanWrite); System.Console.WriteLine("CanSeek: " + bufferedStream.CanSeek); System.Console.WriteLine("Length: " + bufferedStream.Length); System.Console.WriteLine("Position: " + bufferedStream.Position); int firstByte = bufferedStream.ReadByte(); System.Console.WriteLine("Byte:" + firstByte); bufferedStream.Position = 0; System.Console.WriteLine("Position: " + bufferedStream.Position); bufferedStream.WriteByte((byte)(firstByte + 1)); bufferedStream.Flush(); //bufferedStream.Position = 0; //firstByte = bufferedStream.ReadByte(); //bufferedStream.Dispose(); System.Console.WriteLine("Byte:" + firstByte); }
public void avi_idx1() { uint num = (uint)lista_tams.Count; uint tam = num * 16; uint offset = 4; fd.Write(cad2bytearray("idx1"), 0, 4); fd.Write(StructureToByteArray(tam), 0, 4); for (int i = 0; i < num; i++) { fd.Write(cad2bytearray("00dc"), 0, 4); fd.Write(StructureToByteArray(16), 0, 4); fd.Write(StructureToByteArray(offset), 0, 4); fd.Write(StructureToByteArray(lista_tams[i]), 0, 4); offset += lista_tams[i] + 8; } fd.Seek(4, SeekOrigin.Begin); fd.Write(StructureToByteArray(240 + totalsize + tam + 8), 0, 4); fd.Seek(0x2c, SeekOrigin.Begin); // flag = has index fd.WriteByte(0x10); }
private Response TcpRequest(Request request) { //System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); //sw.Start(); for (var intAttempts = 0; intAttempts < _mRetries; intAttempts++) { for (var intDnsServer = 0; intDnsServer < _mDnsServers.Count; intDnsServer++) { //var tcpClient = new TcpClient(AddressFamily.InterNetworkV6) {ReceiveTimeout = _mTimeout*1000}; var tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //tcpClient.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); try { Verbose(";; Connecting to nameserver {0}", _mDnsServers[intDnsServer].Address); var result = tcpClient.BeginConnect(_mDnsServers[intDnsServer].Address, _mDnsServers[intDnsServer].Port, null, null); var success = result.AsyncWaitHandle.WaitOne(_mTimeout*1000, true); if (!success || !tcpClient.Connected) { tcpClient.Close(); Verbose(string.Format(";; Connection to nameserver {0} failed", _mDnsServers[intDnsServer].Address)); continue; } var bs = new BufferedStream(new NetworkStream(tcpClient)); var data = request.Data; bs.WriteByte((byte) ((data.Length >> 8) & 0xff)); bs.WriteByte((byte) (data.Length & 0xff)); bs.Write(data, 0, data.Length); bs.Flush(); var transferResponse = new Response(); var intSoa = 0; var intMessageSize = 0; //Debug.WriteLine("Sending "+ (request.Length+2) + " bytes in "+ sw.ElapsedMilliseconds+" mS"); while (true) { var intLength = bs.ReadByte() << 8 | bs.ReadByte(); if (intLength <= 0) { tcpClient.Close(); Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1))); throw new SocketException(); // next try } intMessageSize += intLength; data = new byte[intLength]; bs.Read(data, 0, intLength); var response = new Response(_mDnsServers[intDnsServer], data); //Debug.WriteLine("Received "+ (intLength+2)+" bytes in "+sw.ElapsedMilliseconds +" mS"); if (response.Header.RCODE != RCode.NoError) return response; if (response.Questions[0].QType != QType.AXFR) { AddToCache(response); return response; } // Zone transfer!! if (transferResponse.Questions.Count == 0) transferResponse.Questions.AddRange(response.Questions); transferResponse.Answers.AddRange(response.Answers); transferResponse.Authorities.AddRange(response.Authorities); transferResponse.Additionals.AddRange(response.Additionals); if (response.Answers[0].Type == Type.SOA) intSoa++; if (intSoa != 2) continue; transferResponse.Header.QDCOUNT = (ushort) transferResponse.Questions.Count; transferResponse.Header.ANCOUNT = (ushort) transferResponse.Answers.Count; transferResponse.Header.NSCOUNT = (ushort) transferResponse.Authorities.Count; transferResponse.Header.ARCOUNT = (ushort) transferResponse.Additionals.Count; transferResponse.MessageSize = intMessageSize; return transferResponse; } } // try catch (SocketException) { continue; // next try } finally { _mUnique++; // close the socket tcpClient.Close(); } } } var responseTimeout = new Response {Error = "Timeout Error"}; return responseTimeout; }
public void Flush () { BufferedStream stream = new BufferedStream (mem); stream.WriteByte (1); stream.WriteByte (2); byte [] bytes = mem.GetBuffer (); AssertEquals ("test#01", 0, bytes.Length); stream.Flush (); bytes = mem.GetBuffer (); AssertEquals ("test#02", 256, bytes.Length); AssertEquals ("test#03", 1, bytes [0]); AssertEquals ("test#04", 2, bytes [1]); mem.Close (); mem = new MemoryStream (); bytes = new byte [] {0, 1, 2, 3, 4, 5}; stream = new BufferedStream (mem); stream.Write (bytes, 0, 2); AssertEquals ("test#05", 2, stream.Length); bytes = mem.GetBuffer (); AssertEquals ("test#06", 256, bytes.Length); AssertEquals ("test#07", 0, bytes [0]); AssertEquals ("test#08", 1, bytes [1]); stream.Write (bytes, 0, 2); bytes = mem.GetBuffer (); AssertEquals ("test#09", 0, bytes [0]); AssertEquals ("test#10", 1, bytes [1]); AssertEquals ("test#11", 0, bytes [2]); AssertEquals ("test#12", 0, bytes [3]); stream.Flush (); bytes = mem.GetBuffer (); AssertEquals ("test#13", 0, bytes [2]); AssertEquals ("test#14", 1, bytes [3]); }
public void Open() { try { mySerialPort.Open(); baseStream = new BufferedStream(mySerialPort.BaseStream, 1024); Encoding enc = new ASCIIEncoding(); writer = new StreamWriter(baseStream, enc); reader = new BinaryReader(baseStream); baseStream.WriteByte((byte)0x19); //ctrl-Y --> perform reset of Patriot baseStream.WriteByte((byte)0x0D); baseStream.WriteByte((byte)0x0A); baseStream.Flush(); // Thread.Sleep(12000); //wait for completion Head h = frames[0]; frames.Remove(h); h = IssueCommand("F1"); //set binary mode if (h != null && h.ErrorIndicator != (byte)0) throw new Exception("Unable to set binary mode: " + h.ExtractErrorMessage()); h = IssueCommand("U1"); //set metric scale (cm) if (h != null && h.ErrorIndicator != (byte)0) throw new Exception("Unable to set metric units: " + h.ExtractErrorMessage()); h = IssueCommand("O*,2"); //position data only reader.ReadBytes(h.ResponseSize); //skip returned h = IssueCommand("L1,1"); //set button on stylus to work if (h != null && h.ErrorIndicator != (byte)0) throw new Exception("Unable to set stylus button mode: " + h.ExtractErrorMessage()); } catch (Exception e) { throw new Exception("Patriot.Open: " + e.Message); } }
public void Flush () { BufferedStream stream = new BufferedStream (mem); stream.WriteByte (1); stream.WriteByte (2); byte [] bytes = mem.GetBuffer (); Assert.AreEqual (0, bytes.Length, "test#01"); stream.Flush (); bytes = mem.GetBuffer (); Assert.AreEqual (256, bytes.Length, "test#02"); Assert.AreEqual (1, bytes [0], "test#03"); Assert.AreEqual (2, bytes [1], "test#04"); mem.Close (); mem = new MemoryStream (); bytes = new byte [] {0, 1, 2, 3, 4, 5}; stream = new BufferedStream (mem); stream.Write (bytes, 0, 2); Assert.AreEqual (2, stream.Length, "test#05"); bytes = mem.GetBuffer (); Assert.AreEqual (256, bytes.Length, "test#06"); Assert.AreEqual (0, bytes [0], "test#07"); Assert.AreEqual (1, bytes [1], "test#08"); stream.Write (bytes, 0, 2); bytes = mem.GetBuffer (); Assert.AreEqual (0, bytes [0], "test#09"); Assert.AreEqual (1, bytes [1], "test#10"); Assert.AreEqual (0, bytes [2], "test#11"); Assert.AreEqual (0, bytes [3], "test#12"); stream.Flush (); bytes = mem.GetBuffer (); Assert.AreEqual (0, bytes [2], "test#13"); Assert.AreEqual (1, bytes [3], "test#14"); }
public void Close7 () { BufferedStream stream = new BufferedStream (mem); mem.Close (); stream.WriteByte (1); }
private static void MyBufferStream() { MemoryStream ms = new MemoryStream(); BufferedStream bs = new BufferedStream(ms, 4096); byte [] b=new byte[10]; for (int i = 0; i < 10; i++) { bs.WriteByte((byte)i); } bs.Position = 0; bs.Read(b, 0, 9); for (int i = 0; i < 10; i++) { Console.WriteLine("读的值是:{0}", b[i]); } Console.WriteLine("值是:{0}", bs.ReadByte()); }
public byte[] SendAndReceiveAttempt(byte[] data) { TcpClient tcpClient = null; try { if (LocalEndPoint != null) tcpClient = new TcpClient(LocalEndPoint); else tcpClient = new TcpClient(); IAsyncResult result = tcpClient.BeginConnect(RemoteEndPoint.Address, RemoteEndPoint.Port, null, null); bool success = result.AsyncWaitHandle.WaitOne(Timeout, true); if (!success || !tcpClient.Connected) { tcpClient.Close(); throw new Exception("Could not connect with server." + (RemoteEndPoint == null ? "" : " Server=" + RemoteEndPoint.Address + ":" + RemoteEndPoint.Port)); } var bs = new BufferedStream(tcpClient.GetStream()); bs.WriteByte((byte) ((data.Length >> 8) & 0xff)); bs.WriteByte((byte) (data.Length & 0xff)); bs.Write(data, 0, data.Length); bs.Flush(); while (true) { int intLength = bs.ReadByte() << 8 | bs.ReadByte(); if (intLength <= 0) { tcpClient.Close(); throw new Exception("Connection to nameserver failed." + (RemoteEndPoint == null ? "" : " Server=" + RemoteEndPoint.Address + ":" + RemoteEndPoint.Port)); } data = new byte[intLength]; bs.Read(data, 0, intLength); return data; } } finally { if (tcpClient != null) { tcpClient.Close(); } } }
public void WriteByte_CantWrite () { ReadOnlyStream ro = new ReadOnlyStream (); BufferedStream stream = new BufferedStream (ro); stream.WriteByte (0); }
public void WriteToTemp(byte[] bytes, String filename, bool createNew = false) { if(createNew && System.IO.File.Exists(filename)) { System.IO.File.Delete(filename); } using (FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write )) { using (BufferedStream bs = new BufferedStream(fs)) { foreach (byte b in bytes) { bs.WriteByte(b); } } } }
public void WriteEntry(TarEntry entry, bool recurse) { string path = null; string file = entry.File; if ((file == null) || (file.Length == 0)) { entry = TarEntry.CreateTarEntry(entry.Name); } else { string name = entry.Name; entry = TarEntry.CreateEntryFromFile(file); entry.Name = name; } if (this.verbose) { this.OnProgressMessageEvent(entry.Name); } if ((this.asciiTranslate && !entry.IsDirectory) && !this.IsBinary(file)) { path = Path.GetTempFileName(); StreamReader reader = File.OpenText(file); Stream stream = new BufferedStream(File.Create(path)); while (true) { string s = reader.ReadLine(); if (s == null) { break; } byte[] bytes = Encoding.ASCII.GetBytes(s); stream.Write(bytes, 0, bytes.Length); stream.WriteByte(10); } reader.Close(); stream.Flush(); stream.Close(); entry.Size = new FileInfo(path).Length; file = path; } string str5 = null; if ((this.rootPath != null) && entry.Name.StartsWith(this.rootPath)) { str5 = entry.Name.Substring(this.rootPath.Length + 1); } if (this.pathPrefix != null) { str5 = (str5 == null) ? (this.pathPrefix + "/" + entry.Name) : (this.pathPrefix + "/" + str5); } if (str5 != null) { entry.Name = str5; } this.tarOut.PutNextEntry(entry); if (entry.IsDirectory) { if (recurse) { TarEntry[] directoryEntries = entry.GetDirectoryEntries(); for (int i = 0; i < directoryEntries.Length; i++) { this.WriteEntry(directoryEntries[i], recurse); } } } else { Stream stream2 = File.OpenRead(file); int num2 = 0; byte[] buffer = new byte[0x8000]; while (true) { int count = stream2.Read(buffer, 0, buffer.Length); if (count <= 0) { break; } this.tarOut.Write(buffer, 0, count); num2 += count; } Console.WriteLine("written " + num2 + " bytes"); stream2.Close(); if ((path != null) && (path.Length > 0)) { File.Delete(path); } this.tarOut.CloseEntry(); } }
//throws ServletException, IOException private int HandleRequest(HttpRequest request, HttpResponse response, HmuxChannel hmuxChannel, BufferedStream rs, BufferedStream ws, byte[] buf, int length, bool isComplete, bool allowBusy) { String traceId = hmuxChannel.GetTraceId(); StringBuilder cb = new StringBuilder(); bool isDebugFiner = true; String uri = Uri.EscapeUriString(request.RawUrl); Trace.TraceInformation("Hmux[{0}] >>U:uri {1}->{2}", traceId, request.RawUrl, uri); WriteRequestString(ws, HmuxChannel.HMUX_URI, uri, traceId); Trace.TraceInformation("Hmux[{0}] >>m:method {1}", traceId, request.HttpMethod); WriteRequestString(ws, HmuxChannel.HMUX_METHOD, request.HttpMethod, traceId); Trace.TraceInformation("Hmux[{0}] >>u:server type {1}", traceId, "IIS"); WriteRequestString(ws, HmuxChannel.CSE_SERVER_TYPE, "IIS", traceId); NameValueCollection serverVariables = request.ServerVariables; String serverPort = serverVariables.Get("SERVER_PORT"); String serverName = serverVariables.Get("SERVER_NAME") + ':' + serverPort; Trace.TraceInformation("Hmux[{0}] >>v:server name {1}", traceId, serverName); WriteRequestString(ws, HmuxChannel.HMUX_SERVER_NAME, serverName, traceId); Trace.TraceInformation("Hmux[{0}] >>g:server port {1}", traceId, serverPort); WriteRequestString(ws, HmuxChannel.CSE_SERVER_PORT, serverPort, traceId); String remoteAddr = serverVariables.Get("REMOTE_ADDR"); Trace.TraceInformation("Hmux[{0}] >>i:remote address {1}", traceId, remoteAddr); WriteRequestString(ws, HmuxChannel.CSE_REMOTE_ADDR, remoteAddr, traceId); String remoteHost = serverVariables.Get("REMOTE_HOST"); if (remoteHost == null) remoteHost = remoteAddr; Trace.TraceInformation("Hmux[{0}] >>h:remote host {1}", traceId, remoteHost); WriteRequestString(ws, HmuxChannel.CSE_REMOTE_HOST, remoteHost, traceId); String protocol = serverVariables.Get("HTTP_VERSION"); Trace.TraceInformation("Hmux[{0}] >>c:protocol {1}", traceId, protocol); WriteRequestString(ws, HmuxChannel.CSE_PROTOCOL, protocol, traceId); HttpClientCertificate clientCertificate = request.ClientCertificate; if (request.IsSecureConnection) { Trace.TraceInformation("Hmux[{0}] >>r:secure", traceId); WriteRequestString(ws, HmuxChannel.CSE_IS_SECURE, "", traceId); WriteRequestHeader(ws, "HTTPS", "on", traceId); WriteRequestHeader(ws, "SSL_SECRETKEYSIZE", clientCertificate.KeySize.ToString(), traceId); } if (clientCertificate.IsPresent) { Trace.TraceInformation("Hmux[{0}] >>r:certificate ({1})", traceId, clientCertificate.Certificate.Length); ws.WriteByte(HmuxChannel.CSE_CLIENT_CERT); WriteHmuxLength(ws, clientCertificate.Certificate.Length); ws.Write(clientCertificate.Certificate, 0, clientCertificate.Certificate.Length); } NameValueCollection headers = request.Headers; foreach (String key in headers.AllKeys) { if ("Connection".Equals(key, StringComparison.OrdinalIgnoreCase)) continue; String[] values = headers.GetValues(key); foreach (String value in values) { WriteRequestHeader(ws, key, value, traceId); } } Stream requestStream = request.InputStream; Stream responseStream = null; bool hasHeader = true; bool hasStatus = false; if (length > 0) { Trace.TraceInformation("Hmux[{0}] >>D: data ({1})", traceId, length); WriteRequestData(ws, HmuxChannel.HMUX_DATA, buf, length, traceId); } int len; int code; while (!isComplete && (len = requestStream.Read(buf, 0, buf.Length)) > 0) { Trace.TraceInformation("Hmux[{0}] >>D: data ({1})", traceId, length); WriteRequestData(ws, HmuxChannel.HMUX_DATA, buf, len, traceId); Trace.TraceInformation("Hmux[{0}] >>Y: (yield)", traceId); ws.WriteByte(HmuxChannel.HMUX_YIELD); ws.Flush(); while (true) { code = rs.ReadByte(); if (code < 0) { Trace.TraceInformation("Hmux[{0}] <<w: end of file", traceId); if (hasStatus) return OK | EXIT; else { Trace.TraceInformation("Hmux[{0}] <<w: unexpected end of file", traceId); return FAIL | EXIT; } } else if (code == HmuxChannel.HMUX_QUIT) { Trace.TraceInformation("Hmux[{0}] <<Q: (keepalive)", traceId); if (hasStatus) return OK | QUIT; else { Trace.TraceInformation("Hmux[{0}] <<Q: unexpected quit file", traceId); return FAIL | QUIT; } } else if (code == HmuxChannel.HMUX_EXIT) { Trace.TraceInformation("Hmux[{0}] <<X: (exit)", traceId); if (hasStatus) { return OK | EXIT; } else { Trace.TraceInformation("Hmux[{0}] <<X: unexpected exit", traceId); return FAIL | EXIT; } } else if (code == HmuxChannel.HMUX_YIELD) { Trace.TraceInformation("Hmux[{0}] <<Y: (yield)", traceId); continue; } int sublen = ReadHmuxLength(rs); if (code == HmuxChannel.HMUX_ACK) { if (isDebugFiner) Trace.TraceInformation("Hmux[{0}] <<A: (ack) ({1})", traceId, sublen); break; } else if (code == HmuxChannel.HMUX_CHANNEL) { int channel = sublen; Trace.TraceInformation("Hmux[{0}] <<C: (channel) ({1})", traceId, channel); } else if (code == HmuxChannel.HMUX_STATUS && hasHeader) { String status = ReadHmuxString(rs, sublen); Trace.TraceInformation("Hmux[{0}] <<s: (status) ({1})", traceId, status); int statusCode = 0; for (int i = 0; i < 3; i++) statusCode = 10 * statusCode + status[i] - '0'; if (statusCode != 200) response.StatusCode = statusCode; hasStatus = true; } else if (code == HmuxChannel.HMUX_HEADER && hasHeader) { String name = ReadHmuxString(rs, sublen); rs.ReadByte(); sublen = ReadHmuxLength(rs); String value = ReadHmuxString(rs, sublen); Trace.TraceInformation("Hmux[{0}] <<H,S: (header) ({1}={2})", traceId, name, value); RelayResponseHeader(response, name, value); } else if (code == HmuxChannel.HMUX_DATA) { Trace.TraceInformation("Hmux[{0}] <<D: (data)({1})", traceId, sublen); if (responseStream == null) responseStream = response.OutputStream; RelayResponseData(rs, responseStream, sublen); } else if (code == HmuxChannel.HMUX_META_HEADER) { String name = ReadHmuxString(rs, sublen); rs.ReadByte(); sublen = ReadHmuxLength(rs); String value = ReadHmuxString(rs, sublen); Trace.TraceInformation("Hmux[{0}] <<M,S: header ({1}={2})", traceId, name, value); if ("cpu-load".Equals(name)) { double loadAvg = 0.001 * long.Parse(value); hmuxChannel.GetPool().SetCpuLoadAvg(loadAvg); } } else { Skip(rs, sublen); } } } ws.WriteByte(HmuxChannel.HMUX_QUIT); ws.Flush(); code = rs.ReadByte(); // #2369 - A slow modem can cause the app-tier and web-tier times // to get out of sync, with the app-tier thinking it's completed // (and starts the keepalive timeout) 30s before the web-tier reads // its data. // As a temporary measure, we start the idle time at the first data // read (later we might mark the time it takes to read an app-tier // packet. If it's short, e.g. 250ms, don't update the time.) hmuxChannel.SetIdleStartTime(DateTime.Now.Ticks); bool isBusy = false; for (; code >= 0; code = rs.ReadByte()) { if (code == HmuxChannel.HMUX_QUIT) { if (isDebugFiner) Trace.TraceInformation("Hmux[{0}] <<Q: (keepalive)", traceId); return isBusy ? BUSY | QUIT : OK | QUIT; } else if (code == HmuxChannel.HMUX_EXIT) { Trace.TraceInformation("Hmux[{0}] <<X: (exit)", traceId); return (isBusy || !hasStatus) ? BUSY | EXIT : OK | EXIT; } else if (code == HmuxChannel.HMUX_YIELD) { Trace.TraceInformation("Hmux[{0}] <<Y: (yield)", traceId); continue; } int sublen = (rs.ReadByte() << 8) + rs.ReadByte(); if (code == HmuxChannel.HMUX_DATA) { if (responseStream == null) responseStream = response.OutputStream; Trace.TraceInformation("Hmux[{0}] <<D: (data)({1})", traceId, sublen); if (!isBusy) RelayResponseData(rs, responseStream, sublen); else Skip(rs, sublen); } else if (code == HmuxChannel.HMUX_STATUS && hasHeader) { hasStatus = true; String status = ReadHmuxString(rs, sublen); Trace.TraceInformation("Hmux[{0}] <<s: (status) ({1})", traceId, status); int statusCode = 0; for (int i = 0; i < 3; i++) statusCode = 10 * statusCode + status[i] - '0'; if (statusCode == 503 && allowBusy) isBusy = true; else if (statusCode != 200) response.StatusCode = statusCode; } else if (code == HmuxChannel.HMUX_HEADER && hasHeader) { String name = ReadHmuxString(rs, sublen); rs.ReadByte(); sublen = ReadHmuxLength(rs); String value = ReadHmuxString(rs, sublen); Trace.TraceInformation("Hmux[{0}] <<H,S: (header) ({1}={2})", traceId, name, value); if (!isBusy) RelayResponseHeader(response, name, value); } else if (code == HmuxChannel.HMUX_META_HEADER) { String name = ReadHmuxString(rs, sublen); rs.ReadByte(); sublen = ReadHmuxLength(rs); String value = ReadHmuxString(rs, sublen); Trace.TraceInformation("Hmux[{0}] <<M,S: header ({1}={2})", traceId, name, value); if ("cpu-load".Equals(name)) { double loadAvg = 0.001 * long.Parse(value); hmuxChannel.GetPool().SetCpuLoadAvg(loadAvg); } } else if (code == HmuxChannel.HMUX_CHANNEL) { int channel = sublen; Trace.TraceInformation("Hmux[{0}] <<C: (channel) ({1})", traceId, channel); } else if (code == 0) { Trace.TraceInformation("Hmux[{0}] <<0: unknown code (0)", traceId); return FAIL | EXIT; } else { Trace.TraceInformation("Hmux[{0}] <<?: unknown code ({1})", traceId, code); Skip(rs, sublen); } } Trace.TraceInformation("Hmux[{0}] end of file", traceId); // server/269q if (hasStatus) return isBusy ? BUSY | EXIT : OK | EXIT; else { Trace.TraceInformation("Hmux[{0}] unexpected end of file", traceId, code); return FAIL | EXIT; } }
private void WriteHmuxLength(BufferedStream stream, int length) { stream.WriteByte((byte)(length >> 8)); stream.WriteByte((byte)length); }
private void WriteRequestData(BufferedStream stream, int code, byte[] data, int length, String traceId) { stream.WriteByte(HmuxChannel.HMUX_DATA); WriteHmuxLength(stream, length); stream.Write(data, 0, length); }
public void WriteByte () { BufferedStream stream = new BufferedStream (mem); stream.WriteByte (1); stream.WriteByte (2); stream.WriteByte (3); stream.Flush (); Assert.AreEqual (256, mem.GetBuffer ().Length, "test#01"); Assert.AreEqual (3, stream.Length, "test#02"); Assert.AreEqual (1, mem.GetBuffer () [0], "test#03"); Assert.AreEqual (2, mem.GetBuffer () [1], "test#04"); Assert.AreEqual (3, mem.GetBuffer () [2], "test#05"); }
private void WriteRequestString(BufferedStream stream, int code, String value, String traceId) { stream.WriteByte((byte)code); if (value == null) { WriteHmuxLength(stream, 0); } else { byte[] bytes = System.Text.Encoding.ASCII.GetBytes(value.ToCharArray()); WriteHmuxLength(stream, bytes.Length); stream.Write(bytes, 0, bytes.Length); } }
/// <summary> /// Write an entry to the archive. This method will call the putNextEntry /// and then write the contents of the entry, and finally call closeEntry()() /// for entries that are files. For directories, it will call putNextEntry(), /// and then, if the recurse flag is true, process each entry that is a /// child of the directory. /// </summary> /// <param name="entry"> /// The TarEntry representing the entry to write to the archive. /// </param> /// <param name="recurse"> /// If true, process the children of directory entries. /// </param> public void WriteEntry(TarEntry entry, bool recurse) { bool asciiTrans = false; string tempFileName = null; string eFile = entry.File; // Work on a copy of the entry so we can manipulate it. // Note that we must distinguish how the entry was constructed. // if (eFile == null || eFile.Length == 0) { entry = TarEntry.CreateTarEntry(entry.Name); } else { // // The user may have explicitly set the entry's name to // something other than the file's path, so we must save // and restore it. This should work even when the name // was set from the File's name. // string saveName = entry.Name; entry = TarEntry.CreateEntryFromFile(eFile); entry.Name = saveName; } if (this.verbose) { OnProgressMessageEvent(entry, null); } if (this.asciiTranslate && !entry.IsDirectory) { asciiTrans = !IsBinary(eFile); // original java source : // MimeType mime = null; // string contentType = null; // // try { // contentType = FileTypeMap.getDefaultFileTypeMap(). getContentType( eFile ); // // mime = new MimeType( contentType ); // // if ( mime.getPrimaryType(). // equalsIgnoreCase( "text" ) ) // { // asciiTrans = true; // } // else if ( this.transTyper != null ) // { // if ( this.transTyper.isAsciiFile( eFile ) ) // { // asciiTrans = true; // } // } // } catch ( MimeTypeParseException ex ) // { // // IGNORE THIS ERROR... // } // // if (this.debug) { // Console.Error.WriteLine("CREATE TRANS? '" + asciiTrans + "' ContentType='" + contentType + "' PrimaryType='" + mime.getPrimaryType()+ "'" ); // } if (asciiTrans) { tempFileName = Path.GetTempFileName(); StreamReader inStream = File.OpenText(eFile); Stream outStream = new BufferedStream(File.Create(tempFileName)); while (true) { string line = inStream.ReadLine(); if (line == null) { break; } byte[] data = Encoding.ASCII.GetBytes(line); outStream.Write(data, 0, data.Length); outStream.WriteByte((byte)'\n'); } inStream.Close(); outStream.Flush(); outStream.Close(); entry.Size = new FileInfo(tempFileName).Length; eFile = tempFileName; } } string newName = null; if (this.rootPath != null) { if (entry.Name.StartsWith(this.rootPath)) { newName = entry.Name.Substring(this.rootPath.Length + 1 ); } } if (this.pathPrefix != null) { newName = (newName == null) ? this.pathPrefix + "/" + entry.Name : this.pathPrefix + "/" + newName; } if (newName != null) { entry.Name = newName; } this.tarOut.PutNextEntry(entry); if (entry.IsDirectory) { if (recurse) { TarEntry[] list = entry.GetDirectoryEntries(); for (int i = 0; i < list.Length; ++i) { this.WriteEntry(list[i], recurse); } } } else { Stream inputStream = File.OpenRead(eFile); int numWritten = 0; byte[] eBuf = new byte[32 * 1024]; while (true) { int numRead = inputStream.Read(eBuf, 0, eBuf.Length); if (numRead <=0) { break; } this.tarOut.Write(eBuf, 0, numRead); numWritten += numRead; } // Console.WriteLine("written " + numWritten + " bytes"); inputStream.Close(); if (tempFileName != null && tempFileName.Length > 0) { File.Delete(tempFileName); } this.tarOut.CloseEntry(); } }
private void WriteSSLCertificate(BufferedStream stream, byte[] cert, String traceId) { Trace.TraceInformation("Hmux[{0}] >>t:certificate({1})", traceId, cert.Length); stream.WriteByte(HmuxChannel.CSE_CLIENT_CERT); WriteHmuxLength(stream, cert.Length); stream.Write(cert, 0, cert.Length); }
private Response TcpRequest(Request request) { //System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); //sw.Start(); byte[] responseMessage = new byte[512]; for (int intAttempts = 0; intAttempts < m_Retries; intAttempts++) { for (int intDnsServer = 0; intDnsServer < m_DnsServers.Count; intDnsServer++) { using( TcpClient tcpClient = new TcpClient() ) { tcpClient.ReceiveTimeout = m_Timeout * 1000; try { IAsyncResult result = tcpClient.BeginConnect(m_DnsServers[intDnsServer].Address, m_DnsServers[intDnsServer].Port, null, null); bool success = result.AsyncWaitHandle.WaitOne(m_Timeout*1000, true); if (!success || !tcpClient.Connected) { Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1))); continue; } BufferedStream bs = new BufferedStream(tcpClient.GetStream()); byte[] data = request.Data; bs.WriteByte((byte)((data.Length >> 8) & 0xff)); bs.WriteByte((byte)(data.Length & 0xff)); bs.Write(data, 0, data.Length); bs.Flush(); Response TransferResponse = new Response(); int intSoa = 0; int intMessageSize = 0; //Debug.WriteLine("Sending "+ (request.Length+2) + " bytes in "+ sw.ElapsedMilliseconds+" mS"); while (true) { int intLength = bs.ReadByte() << 8 | bs.ReadByte(); if (intLength <= 0) { Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1))); throw new SocketException(); // next try } intMessageSize += intLength; data = new byte[intLength]; bs.Read(data, 0, intLength); Response response = new Response(m_DnsServers[intDnsServer], data); //Debug.WriteLine("Received "+ (intLength+2)+" bytes in "+sw.ElapsedMilliseconds +" mS"); if (response.header.RCODE != RCode.NoError) return response; if (response.Questions[0].QType != QType.AXFR) { AddToCache(response); return response; } // Zone transfer!! if(TransferResponse.Questions.Count==0) TransferResponse.Questions.AddRange(response.Questions); TransferResponse.Answers.AddRange(response.Answers); TransferResponse.Authorities.AddRange(response.Authorities); TransferResponse.Additionals.AddRange(response.Additionals); if (response.Answers[0].Type == Type.SOA) intSoa++; if (intSoa == 2) { TransferResponse.header.QDCOUNT = (ushort)TransferResponse.Questions.Count; TransferResponse.header.ANCOUNT = (ushort)TransferResponse.Answers.Count; TransferResponse.header.NSCOUNT = (ushort)TransferResponse.Authorities.Count; TransferResponse.header.ARCOUNT = (ushort)TransferResponse.Additionals.Count; TransferResponse.MessageSize = intMessageSize; return TransferResponse; } } } // try catch (SocketException) { continue; // next try } finally { m_Unique++; } } } } Response responseTimeout = new Response(); responseTimeout.Error = "Timeout Error"; return responseTimeout; }
public void Save(Map mapToSave, string fileName) { if (mapToSave == null) throw new ArgumentNullException("mapToSave"); if (fileName == null) throw new ArgumentNullException("fileName"); using (FileStream mapStream = File.Create(fileName)) { using (GZipStream gs = new GZipStream(mapStream, CompressionMode.Compress)) { // Buffering necessary to avoid overhead of writing byte-at-a-time using (BufferedStream bs = new BufferedStream(gs, WriteBufferSize)) { BinaryWriter bw = new BinaryWriter(bs); // Write the format version bw.Write(1050); // Write the map dimensions bw.Write((short)mapToSave.Width); bw.Write((short)mapToSave.Length); bw.Write((short)mapToSave.Height); // Write spawn coordinates Vector3I spawn = mapToSave.Spawn.ToBlockCoords(); bw.Write((short)spawn.X); bw.Write((short)spawn.Y); bw.Write((short)spawn.Z); bw.Write((short)mapToSave.Spawn.R); bw.Write((short)mapToSave.Spawn.L); // Write the map data for (int i = 0; i < mapToSave.Volume; i++) { bs.WriteByte(mapToSave.Blocks[i]); bs.WriteByte(0); bs.WriteByte(0xFF); bs.WriteByte(0xFF); } } } } }
/// <summary> /// Reades all data from the specified stream and writes it to source stream. Period handlign and period terminator is added as required. /// </summary> /// <param name="stream">Stream which data to write to source stream.</param> /// <param name="maxSize">Maximum muber of bytes to read from <b>stream</b> and write source stream.</param> /// <returns>Returns number of bytes written to source stream. Note this value differs from /// <b>stream</b> readed bytes count because of period handling and period terminator. /// </returns> /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception> /// <exception cref="InvalidOperationException">Raised when there already is pending write operation.</exception> /// <exception cref="LineSizeExceededException">Raised when <b>stream</b> contains line with bigger line size than allowed.</exception> /// <exception cref="DataSizeExceededException">Raised when <b>stream</b> has more data than <b>maxSize</b> allows..</exception> public int WritePeriodTerminated(Stream stream,int maxSize) { if(stream == null){ throw new ArgumentNullException("stream"); } lock(this){ if(m_IsWriteActive){ throw new InvalidOperationException("There is pending write operation, multiple write operations not allowed !"); } m_IsWriteActive = true; } try{ BufferedStream bufferedStoreStream = new BufferedStream(m_pStream,32000); StreamHelper reader = new StreamHelper(stream); int totalWrittenCount = 0; int readedCount = 0; int rawReadedCount = 0; while(true){ // Read data block. readedCount = this.ReadLineInternal(m_pLineBuffer,SizeExceededAction.ThrowException,out rawReadedCount,false); // We reached end of stream, no more data. if(readedCount == 0){ break; } // Maximum allowed data size exceeded. if((totalWrittenCount + rawReadedCount) > maxSize){ throw new DataSizeExceededException(); } // If line starts with period(.), additional period is added. if(m_pLineBuffer[0] == '.'){ bufferedStoreStream.WriteByte((byte)'.'); totalWrittenCount++; } // Write readed line to buffered stream. bufferedStoreStream.Write(m_pLineBuffer,0,readedCount); bufferedStoreStream.Write(m_LineBreak,0,m_LineBreak.Length); totalWrittenCount += (readedCount + m_LineBreak.Length); } // Write terminator ".<CRLF>". We have start <CRLF> already in stream. bufferedStoreStream.Write(new byte[]{(byte)'.',(byte)'\r',(byte)'\n'},0,3); bufferedStoreStream.Flush(); m_pStream.Flush(); // Log if(this.Logger != null){ this.Logger.AddWrite(totalWrittenCount,null); } return totalWrittenCount; } finally{ m_IsWriteActive = false; } }
public void WriteByte () { BufferedStream stream = new BufferedStream (mem); stream.WriteByte (1); stream.WriteByte (2); stream.WriteByte (3); stream.Flush (); AssertEquals ("test#01", 256, mem.GetBuffer ().Length); AssertEquals ("test#02", 3, stream.Length); AssertEquals ("test#03", 1, mem.GetBuffer () [0]); AssertEquals ("test#04", 2, mem.GetBuffer () [1]); AssertEquals ("test#05", 3, mem.GetBuffer () [2]); }