/// <summary> /// Writes the serialized Python request to the named pipe. Waits from the request to be read on Python side. /// Then reads the response from python(json) an deserializes it to PythonRespnse /// </summary> /// <param name="request"></param> /// <param name="ct"></param> /// <returns></returns> public PythonResponse RequestAsync(PythonRequest request, CancellationToken ct) { using (CancellationTokenRegistration ctr = ct.Register(() => OnCancellationRequested())) { using (var streamWriter = new StreamWriter(ClientStream, _utf8Encoding, _defaultBufferSize, leaveOpen: true) { AutoFlush = true }) { Trace.TraceInformation("Sending information to Python."); streamWriter.WriteLine(request.Serialize()); } ct.ThrowIfCancellationRequested(); bool isWindows = true; #if NETCOREAPP if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { isWindows = false; } #endif if (isWindows) { ClientStream.WaitForPipeDrain(); } using (var streamReader = new StreamReader(ClientStream, _utf8Encoding, false, _defaultBufferSize, leaveOpen: true)) { return(PythonResponse.Deserialize(streamReader.ReadLine())); } } }
public void Close() { if (Client != null) { if (Client.Connected) { Logout(); Client.Close(); Client = null; } } if (ClientStream != null) { ClientStream.Close(); ClientStream = null; } if (Writer != null) { Writer.Close(); Writer = null; } if (Reader != null) { Reader.Close(); Reader = null; } disposed = true; }
private void FinializeServerEncryption(EncryptionKeyResponsePacket encryptionKeyResponsePacket) { // Here, we have all the details we need to initialize our // proxy<->server crypto stream. This happens *after* we have // already completed the crypto handshake with the client. // Wrap the server stream in a crypto stream ServerStream = new NetworkManager(new AesStream(Server, ServerSharedKey)); Log.Write("Encrypted server connection established."); // Write the response. This is the first encrypted packet // sent to the client. The correct response is to send // an 0xFC EncryptionKeyResponse with both fields as empty // arrays. var response = new EncryptionKeyResponsePacket { SharedSecret = new byte[0], VerificationToken = new byte[0] }; ClientStream.WritePacket(response, Craft.Net.PacketDirection.Clientbound); Client.Flush(); // Wrap the client stream in a crypto stream ClientStream = new NetworkManager(new AesStream(Client, ClientSharedKey)); Log.Write("Encrypted client connection established."); // And now we're done with encryption and everything can // continue normally. }
public void Dispose() { Close(); ((IDisposable)Client)?.Dispose(); ClientStream?.Dispose(); }
} // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!DisposedValue) { if (disposing) { try { ClientStream.Close(); ClientStream.Dispose(); Client.Disconnect(); Client.Dispose(); } finally { ConnectionInfo = null; AuthenticationMethod = null; ClientStream = null; Client = null; } } DisposedValue = true; } }
private void ClientErrorOccurred(object sender, ExceptionEventArgs e) { System.Diagnostics.Debug.WriteLine(e.Exception.Message); if (e.Exception is Renci.SshNet.Common.SshConnectionException) { try { ClientStream.Close(); ClientStream.Dispose(); } finally { ClientStream = null; } try { Client.Disconnect(); Client.Dispose(); } finally { ConnectionInfo = null; AuthenticationMethod = null; Client = null; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsConnected")); } } else { throw new NotImplementedException(); } }
public void CloseForm() { Cts.Cancel(); Thread.Sleep(1000); ClientStream.Close(); ClientStream.Dispose(); }
private static void ClientLoop(ILogger packetLogger) { var diagnosticProvider = new InfusionDiagnosticPushStreamProvider(Configuration, Console); serverDiagnosticPushStream = new CompositeDiagnosticPushStream(new ConsoleDiagnosticPushStream(packetLogger, "proxy -> server"), new InfusionBinaryDiagnosticPushStream(DiagnosticStreamDirection.ClientToServer, diagnosticProvider.GetStream)); serverDiagnosticPullStream = new ConsoleDiagnosticPullStream(packetLogger, "server -> proxy"); serverConnection = new ServerConnection(ServerConnectionStatus.Initial, serverDiagnosticPullStream, serverDiagnosticPushStream); serverConnection.PacketReceived += ServerConnectionOnPacketReceived; clientConnection = new UltimaClientConnection(UltimaClientConnectionStatus.Initial, new ConsoleDiagnosticPullStream(packetLogger, "client -> proxy"), new CompositeDiagnosticPushStream(new ConsoleDiagnosticPushStream(packetLogger, "proxy -> client"), new InfusionBinaryDiagnosticPushStream(DiagnosticStreamDirection.ServerToClient, diagnosticProvider.GetStream))); clientConnection.PacketReceived += ClientConnectionOnPacketReceived; diagnosticProvider.ClientConnection = clientConnection; diagnosticProvider.ServerConnection = serverConnection; Task.Run(() => ServerLoop()); try { while (true) { var client = listener.AcceptTcpClient(); ClientStream = client.GetStream(); int receivedLength; var receiveBuffer = new byte[65535]; while ((receivedLength = ClientStream.Read(receiveBuffer, 0, receiveBuffer.Length)) > 0) { var memoryStream = new MemoryStream(receiveBuffer, 0, receivedLength, false); clientConnection.ReceiveBatch(new MemoryStreamToPullStreamAdapter(memoryStream)); } Thread.Yield(); } } catch (IOException ioex) when(ioex.InnerException is SocketException socex && socex.SocketErrorCode == SocketError.ConnectionReset) { Console.Error("Connection to client lost."); throw; } catch (Exception ex) { Console.Error(serverDiagnosticPullStream.Flush()); Console.Error(ex.ToString()); throw; } finally { diagnosticProvider.Dispose(); } }
public void Dispose() { Close(); (Client as IDisposable)?.Dispose(); 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); } } } }
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; }
private void c_OnDisconnect(ClientStream s) { try { lock (sync) { if (connectedClientNodes.Contains(s)) { //Check it is actually the same node // var search = connectedClientNodes.Where(n => n.Node.ID == s.Node.ID && s.Node.Secret == s.Node.Secret).FirstOrDefault(); // if (null == search) { logger.Debug("Server dropped client {0}", s.Node.ID); connectedClientNodes.Remove(s); s.OnDisconnect -= c_OnDisconnect; var info = new UpdateVerb(); info.Nodes.Add(new Node { ID = s.Node.ID, Online = false }); NetworkRequest req = info.CreateRequest(); req.OverlordID = serverNode.ID; req.SourceID = serverNode.ID; SendToOverlordClients(req); SendToStandardClients(req); } } } } catch { } }
public void CloseConnection() { lock (clientLocker) { if (ClientConnected) { try { ClientWriter.WriteLine("-- " + Properties.strings.cya); ClientWriter.Flush(); } catch (IOException) { } ConnectedServer.WriteToAllClients("-- " + string.Format(Properties.strings.disconnectedClient, Name + "@" + ClientIep.Address, ClientIep.Port)); ClientWriter.Close(); ClientReader.Close(); ClientStream.Close(); ClientSocket.Close(); ClientConnected = false; ConnectedServer.connectedClients.Remove(this); } } ConnectedServer.RefreshInfo(); }
/// <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 RespondBlockPage() { String bp = "<html><body>Block Page</body></html>"; SendHeader("", bp.Length, "404"); SendBlockPage(bp); ClientStream.Flush(); ClientStream.Close(); }
private string GetResponceFromServer() { byte[] buffer = new byte[128]; ClientStream.Read(buffer); buffer = buffer.Where(b => b != 0).ToArray(); string responce = Encoding.UTF8.GetString(buffer); return(responce); }
private void OnJobCompleted(object sender, JobCompletedEventArgs jobCompletedEventArgs) { if (!jobCompletedEventArgs.Completed) { CentipedeSerializer.Serialize(ClientStream, false); } ClientStream.Close(); _messagePipe.Close(); System.Windows.Forms.Application.Exit(); }
public override void SetTerminalWindowSize(int columns, int rows, int width, int height) { Columns = columns; Rows = rows; if (IsConnected) { ClientStream.SendWindowChangeRequest((uint)columns, (uint)rows, (uint)width, (uint)height); } }
private void SendMessage() { if (string.IsNullOrWhiteSpace(MessageBox)) { return; } ClientStream.Write(Encoding.UTF8.GetBytes(MessageBox.Trim())); ClientStream.Flush(); MessageBox = string.Empty; }
public void OnPipeDisposed() { if (ClientStream != null && ClientStream.IsConnected) { ClientStream?.Close(); } ClientStream?.Close(); ClientStream?.Dispose(); ClientStream = null; }
protected virtual async Task CopyContentFromClientToServer() { //Debug.WriteLine("Reading Request Content"); long contentLength; if (!long.TryParse(Prologue.Headers.FirstOrDefault(x => x.Key == "Content-Length").Value, out contentLength)) { contentLength = -1; } await ClientStream.CopyHttpMessageToAsync(ClientSocket, RemoteStream, contentLength); }
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); }
public void Dispose() { if (ClientStream != null) { ClientStream.Close(); } if (Client != null) { Client.Close(); GwentServer = null; } }
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(); } }
protected virtual void End() { RemoteStream.Close(); RemoteSocket.Shutdown(SocketShutdown.Both); RemoteSocket.Close(); ClientStream.Close(); ClientSocket.Shutdown(SocketShutdown.Both); ClientSocket.Close(); }
public void RespondToRequest() { string fpath = ""; string mimetype = ""; if (localPath != null) { fpath = wbmap.GetPath(localPath); mimetype = wbmap.GetMime(localPath); } if (fpath != "" && mimetype != "") { String retstring = ""; if (mimetypeAscii(mimetype) == true) { if (GetFileStream(fpath, out retstring) == true) { SendHeader(mimetype, retstring.Length, "200"); SendBody(retstring); ClientStream.Flush(); ClientStream.Close(); } else { RespondBlockPage(); } } else { byte[] bout = null; if (GetBinaryFile(fpath, out bout) == true) { SendHeader(mimetype, bout.Length, "200"); SendBodyBinary(bout); ClientStream.Flush(); ClientStream.Close(); } else { RespondBlockPage(); } } } else { RespondBlockPage(); } }
protected override void DoAction() { CentipedeSerializer.Serialize(ClientStream, true); //ClientStream.WaitForPipeDrain(); try { if (!String.IsNullOrWhiteSpace(OutVars)) { var variables = this.OutVars.Split(',').Select(s => s.Trim()).ToList(); CentipedeSerializer.Serialize(ClientStream, variables.Count); foreach (var variable in variables) { object o = Variables[variable]; try { CentipedeSerializer.Serialize(ClientStream, o); } catch (SerializationException e) { var message = string.Format( "Cannot send variable {0} to parent job, type {1} is not supported.", variable, o.GetType()); throw new FatalActionException(message, e, this); } } } else { CentipedeSerializer.Serialize(ClientStream, 0); } } catch (IOException e) { OnMessage(new MessageEventArgs { Message = string.Format( "Sending variables to parent raised IOException: {0}", e.Message), Level = MessageLevel.Debug }); } finally { ClientStream.Close(); } }
public async Task Initialize() { await ClientStream.ConnectAsync(); if (ClientStream.IsConnected) { ClientStreamWriter = new StreamWriter(ClientStream); ClientStreamReader = new StreamReader(ClientStream); } else { throw new TimeoutException($"Client connection to server timed out after {Timeout}."); } }
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 void UpdateClient() { while (Client.DataAvailable) { var packet = ClientStream.ReadPacket(Craft.Net.PacketDirection.Serverbound); Log.LogPacket(packet, true); if (packet is EncryptionKeyResponsePacket) { if (!FinializeClientEncryption((EncryptionKeyResponsePacket)packet)) { if (ConnectionClosed != null) { ConnectionClosed(this, null); } Worker.Abort(); return; } } else { var eventArgs = new IncomingPacketEventArgs(packet, true); if (IncomingPacket != null) { IncomingPacket(this, eventArgs); } lock (Server) { if (!eventArgs.Handled) { ServerStream.WritePacket(packet, Craft.Net.PacketDirection.Serverbound); } // We use a BufferedStream to make sure packets get sent in one piece, rather than // a field at a time. Flushing it here sends the assembled packet. Server.Flush(); } if (packet is DisconnectPacket) { Console.WriteLine("Client disconnected: " + ((DisconnectPacket)packet).Reason); if (ConnectionClosed != null) { ConnectionClosed(this, null); } Worker.Abort(); } } } }