public void Ok(string html) { if (RequestLocked) { throw new Exception("You cannot call this function after request is made to server."); } if (html == null) { html = string.Empty; } var result = Encoding.Default.GetBytes(html); var connectStreamWriter = new StreamWriter(ClientStream); var s = string.Format("HTTP/{0}.{1} {2} {3}", RequestHttpVersion.Major, RequestHttpVersion.Minor, 200, "Ok"); connectStreamWriter.WriteLine(s); connectStreamWriter.WriteLine("Timestamp: {0}", DateTime.Now); connectStreamWriter.WriteLine("content-length: " + result.Length); connectStreamWriter.WriteLine("Cache-Control: no-cache, no-store, must-revalidate"); connectStreamWriter.WriteLine("Pragma: no-cache"); connectStreamWriter.WriteLine("Expires: 0"); connectStreamWriter.WriteLine(RequestIsAlive ? "Connection: Keep-Alive" : "Connection: close"); connectStreamWriter.WriteLine(); connectStreamWriter.Flush(); ClientStream.Write(result, 0, result.Length); CancelRequest = true; }
/// <summary> /// This will wait for the SensorNetworkServer, and when it finds it, it will connect! /// This code was directly lifted from how this functionality works in the Teensy's source code. /// </summary> private void WaitForAndConnectToServer() { bool connected = false; // Wait for the SensorNetworkServer to be up while (!connected && CurrentlyRunning) { try { Client = new TcpClient(ClientIP, ClientPort); ClientStream = Client.GetStream(); connected = true; // Ask the SensorNetworkServer for its initialization byte[] askForInit = Encoding.ASCII.GetBytes("Send Sensor Configuration"); ClientStream.Write(askForInit, 0, askForInit.Length); ClientStream.Flush(); } catch { logger.Info($"{Utilities.GetTimeStamp()}: SimulationSensorNetwork is waiting for the SensorNetworkServer."); if (Client != null) { Client.Dispose(); } if (ClientStream != null) { ClientStream.Dispose(); } } } }
public void SendToClient(Packet rawPacket) { if (clientConnection == null || ClientStream == null) { return; } var filteredPacket = serverPacketHandler.FilterOutput(rawPacket); if (filteredPacket.HasValue) { lock (serverConnectionLock) { using (var memoryStream = new MemoryStream(1024)) { clientConnection.Send(filteredPacket.Value, memoryStream); var buffer = memoryStream.GetBuffer(); #if DUMP_RAW Console.Info("proxy -> client"); Console.Info(buffer.Take((int)memoryStream.Length).Select(x => x.ToString("X2")).Aggregate((l, r) => l + " " + r)); #endif ClientStream.Write(buffer, 0, (int)memoryStream.Length); } } } }
private void SendMessage() { if (string.IsNullOrWhiteSpace(MessageBox)) { return; } ClientStream.Write(Encoding.UTF8.GetBytes(MessageBox.Trim())); ClientStream.Flush(); MessageBox = string.Empty; }
public void SendMessage(Package pkg) { string Str = XamlWriter.Save(pkg); byte[] buff = Encoding.Default.GetBytes(Str); short Size = (short)buff.Length; byte[] BSize = BitConverter.GetBytes(Size); ClientStream.Write(BSize, 0, BSize.Length); ClientStream.Write(buff, 0, buff.Length); Console.WriteLine("Отправлен пакет размером :" + buff.Length); }
private void SendRequest(string login, string password, Purpose purpose) { try { byte[] buffer = Encoding.UTF8.GetBytes($"{login} {password} {purpose}"); ClientStream.Write(buffer); } catch { throw new Exception(); } }
private void Send_Click(object sender, EventArgs e) { if (sendArea.Text == string.Empty) { UiRuntimeChange.Log("You Have to Write Something To Send It ....\n", LogType.Error, receieveArea); return; } var encodingValue = ((EncodingObject)SendEncoding.SelectedItem).Name; var encoder = Encoding.GetEncoding(encodingValue); var bytes = encoder.GetBytes(ConvertHexCharacters(sendArea.Text)); ClientStream.Write(bytes, 0, bytes.Length); sendArea.Clear(); UiRuntimeChange.Log("Your Message Sended Successfully ....\n", LogType.Message, receieveArea); }
private bool DoHandshake() { while (Client.Available == 0 && Client.Connected) { } if (!Client.Connected) { return(false); } byte[] handshake; using (var handshakeBuffer = new MemoryStream()) { while (Client.Available > 0) { var buffer = new byte[Client.Available]; ClientStream.Read(buffer, 0, buffer.Length); handshakeBuffer.Write(buffer, 0, buffer.Length); } handshake = handshakeBuffer.ToArray(); } if (!Encoding.UTF8.GetString(handshake).StartsWith("GET")) { return(false); } var response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine + "Connection: Upgrade" + Environment.NewLine + "Upgrade: websocket" + Environment.NewLine + "Sec-WebSocket-Accept: " + Convert.ToBase64String( SHA1.Create().ComputeHash( Encoding.UTF8.GetBytes( new Regex("Sec-WebSocket-Key: (.*)").Match(Encoding.UTF8.GetString(handshake)).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" ) ) ) + Environment.NewLine + Environment.NewLine); ClientStream.Write(response, 0, response.Length); return(true); }
private void SendHeader(string mimeHeader, int totBytes, string statusCode) { String sBuffer = ""; // if Mime type is not provided set default to text/html if (mimeHeader.Length == 0) { mimeHeader = "text/html"; // Default Mime Type is text/html } sBuffer = sBuffer + httpVersion + statusCode + "\r\n"; sBuffer = sBuffer + "Server: spellsec-b\r\n"; sBuffer = sBuffer + "Content-Type: " + mimeHeader + "\r\n"; sBuffer = sBuffer + "Accept-Ranges: bytes\r\n"; sBuffer = sBuffer + "Content-Length: " + totBytes + "\r\n\r\n"; Byte[] bSendData = Encoding.ASCII.GetBytes(sBuffer); ClientStream.Write(bSendData, 0, sBuffer.Length); }
public static void SendToClient(Packet rawPacket) { if (clientConnection == null || ClientStream == null) { return; } var filteredPacket = serverPacketHandler.FilterOutput(rawPacket); if (filteredPacket.HasValue) { lock (serverConnectionLock) { using (var memoryStream = new MemoryStream(1024)) { clientConnection.Send(filteredPacket.Value, memoryStream); ClientStream.Write(memoryStream.GetBuffer(), 0, (int)memoryStream.Length); } } } }
public void Ok(string Html) { if (Html == null) { Html = string.Empty; } var result = Encoding.Default.GetBytes(Html); StreamWriter connectStreamWriter = new StreamWriter(ClientStream); var s = String.Format("HTTP/{0}.{1} {2} {3}", RequestHttpVersion.Major, RequestHttpVersion.Minor, 200, "Ok"); connectStreamWriter.WriteLine(s); connectStreamWriter.WriteLine(String.Format("Timestamp: {0}", DateTime.Now.ToString())); connectStreamWriter.WriteLine("content-length: " + result.Length); connectStreamWriter.WriteLine("Cache-Control: no-cache, no-store, must-revalidate"); connectStreamWriter.WriteLine("Pragma: no-cache"); connectStreamWriter.WriteLine("Expires: 0"); if (RequestIsAlive) { connectStreamWriter.WriteLine("Connection: Keep-Alive"); } else { connectStreamWriter.WriteLine("Connection: close"); } connectStreamWriter.WriteLine(); connectStreamWriter.Flush(); ClientStream.Write(result, 0, result.Length); CancelRequest = true; }
internal void SendResponse() { // Create a new memory stream which will be wrapped up by BinaryWrite to construct the payload byte array. // The initial size of the stream is the same as the maximum payload buffer size as that is the size // in which the client (the driver) reads (the response) data from the service as well. int sizeResponseStream = GatewayPayloadConst.payloadHeaderSize + (int)SizePayloadBuffer; MemoryStream msPayload = new MemoryStream(sizeResponseStream); BinaryWriter writer = new BinaryWriter(msPayload); uint padding = 0xDEADBEEF; // // Write the header // writer.Write((uint)Mode); // Write the padding writer.Write(padding); writer.Write(OffsetToRW); writer.Write(SizePayloadBuffer); // Explicitly append the terminating null since GetBytes will not include it in the byte array returned. byte[] arrDeviceID = System.Text.Encoding.Unicode.GetBytes(DeviceID + "\0"); LengthDeviceID = (uint)arrDeviceID.Length; writer.Write(LengthDeviceID); writer.Write(SRBAddress.ToUInt64()); writer.Write(arrDeviceID); // Finally, write the EndOfPayloadMarker writer.Write(GatewayPayloadConst.EndOfPayloadMarker); // // Write the payload if one was expected to be sent // if ((SizePayloadBuffer > 0) && (PayloadData != null)) { // Move the writer to be after the header msPayload.Seek(GatewayPayloadConst.payloadHeaderSize, SeekOrigin.Begin); // Console.WriteLine("SFBlockstoreService::SendResponse: Writer is at position {0} to write the payload of length {1}", msPayload.Position, SizePayloadBuffer); // And then write the payload writer.Write(PayloadData); } // Get the entire buffer as opposed to getting only the used bytes (which is what ToArray returns). byte[] arrPayload = msPayload.GetBuffer(); writer.Close(); // Send away the response if (ClientStream != null) { //Use sync call because on return caller might tear down the socket. //ClientStream.WriteAsync(arrPayload, 0, arrPayload.Length); ClientStream.Write(arrPayload, 0, arrPayload.Length); } else { SendResponseOverNamedPipe(arrPayload); } }
private void SendBody(string body) { Byte[] bSendData = Encoding.ASCII.GetBytes(body); ClientStream.Write(bSendData, 0, body.Length); }
private void SimulationSensorMonitor() { // First, we want to connect to the SensorNetworkServer if (CurrentlyRunning) { WaitForAndConnectToServer(); } // Next, we want to request initialization and receive it byte[] receivedInit = new byte[0]; if (CurrentlyRunning) { receivedInit = RequestAndAcquireSensorInitialization(); } // At this point, we have the initialization and can initialize the sensors if (CurrentlyRunning) { InitializeSensors(receivedInit); } // Now we can grab the CSV data for ONLY the initialized sensors... if (CurrentlyRunning) { ReadFakeDataFromCSV(); } // Keep track of the indexes for each data array, because we are only extracting a small subsection of each one. // We want to know what subsection we just got so we can get the next subsection in the next iteration int?elTempIdx = 0; int?azTempIdx = 0; int?elEncIdx = 0; int?azEncIdx = 0; int?elAccIdx = 0; int?azAccIdx = 0; int?cbAccIdx = 0; // This will tell us if we are rebooting or not. We will only reboot if the connection is randomly terminated. bool reboot = false; // Now we enter the "super loop" while (CurrentlyRunning) { // Convert subarrays to bytes SimulationSubArrayData subArrays = BuildSubArrays(ref elTempIdx, ref azTempIdx, ref elEncIdx, ref azEncIdx, ref elAccIdx, ref azAccIdx, ref cbAccIdx); SensorStatuses statuses = new SensorStatuses { // TODO: Write the values of each sensor status in here so it can get be encoded (issue #376) }; byte[] dataToSend = ConvertDataArraysToBytes( subArrays.ElevationAccl, subArrays.AzimuthAccl, subArrays.CounterBAccl, subArrays.ElevationTemps, subArrays.AzimuthTemps, subArrays.ElevationEnc, subArrays.AzimuthEnc, statuses ); // We have to check for CurrentlyRunning down here because we don't know when the connection is going to be terminated, and // it could very well be in the middle of the loop. if (CurrentlyRunning) { try { // Send arrays ClientStream.Write(dataToSend, 0, dataToSend.Length); Thread.Sleep(SensorNetworkConstants.DataSendingInterval); } // This will be reached if the connection is unexpectedly terminated (like it is during sensor reinitialization) catch { CurrentlyRunning = false; reboot = true; } } } // If the server disconnects, that triggers a reboot if (reboot) { CurrentlyRunning = true; Client.Dispose(); ClientStream.Dispose(); SimulationSensorMonitor(); } }
private void SendBodyBinary(byte[] body) { ClientStream.Write(body, 0, body.Length); }
public override void SendData(byte[] data) { ClientStream.Write(data, 0, data.Length); ClientStream.Flush(); }
private void SendBlockPage(String blockpage) { Byte[] bSendData = Encoding.ASCII.GetBytes(blockpage); ClientStream.Write(bSendData, 0, bSendData.Length); }