public static void WriteToClient(System.Net.Sockets.TcpClient client, string data) { NetworkStream networkStream = client.GetStream(); Byte[] sendBytes = Encoding.ASCII.GetBytes(data); networkStream.Write(sendBytes, 0, sendBytes.Length); networkStream.Flush(); }
private static void PerformHandshake(System.Net.Sockets.TcpClient client, byte[] data) { //TODO support different versions? Dictionary<string, string> headers = new Dictionary<string, string>(); DecodeHandshake(data, headers); string kkey = headers["Sec-WebSocket-Key"].Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; byte[] combined = Encoding.UTF8.GetBytes(kkey); var sha = SHA1.Create(); sha.Initialize(); sha.TransformFinalBlock(combined, 0, combined.Length); Dictionary<string, string> respHeaders = new Dictionary<string, string>(); respHeaders["Upgrade"] = "websocket"; respHeaders["Connection"] = "Upgrade"; respHeaders["Sec-WebSocket-Accept"] = Convert.ToBase64String(sha.Hash); string responseString = BuildResponseString(respHeaders); Console.WriteLine(responseString); byte[] responseBytes = Encoding.UTF8.GetBytes(responseString); client.GetStream().Write(responseBytes, 0, responseBytes.Length); }
public MockTcpClient(System.Net.Sockets.TcpClient client) : base() { this.Client = client; this.Stream = client.GetStream(); this.ConnectionState = ConnectionState.ConnectionLoggedIn; this.PacketSerializer = new MockPacketSerializer(); }
/// <summary> /// Initializes the TcpClient and sets up an SslStream against the certificate /// </summary> /// <param name="client"></param> /// <param name="certificate"></param> public CommandServerClient(System.Net.Sockets.TcpClient client, X509Certificate2 certificate) : base() { this.Client = client; this.RemoteEndPoint = (IPEndPoint) client.Client.RemoteEndPoint; this.PacketSerializer = new CommandServerPacketSerializer(); this.Certificate = certificate; this.Stream = this.Authenticate(new SslStream(client.GetStream(), false)); }
static void Send(System.Net.Sockets.TcpClient client, string text) { var stream = client.GetStream(); var bytes = System.Text.Encoding.Default.GetBytes(text); stream.Write(bytes, 0, bytes.Length); var buffer = new byte[256]; var count = stream.Read(buffer, 0, buffer.Length); var data = new byte[count]; Array.Copy(buffer, data, data.Length); var result = System.Text.Encoding.Default.GetString(data); Console.WriteLine(result); }
/// <summary> /// Establishes the SSL connection for this client. /// </summary> protected override Stream ConnectClient(System.Net.Sockets.TcpClient client) { // A client has connected. Create the // SslStream using the client's network stream. SslStream sslStream = new SslStream(client.GetStream(), false, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback); // Authenticate the server but don't require the client to authenticate. sslStream.AuthenticateAsServer(_cert, _certVerify.CertRequired, SslProtocols.Default, false); // // Display the properties and settings for the authenticated stream. DisplaySslInfo(sslStream); if (!sslStream.IsEncrypted) throw new ApplicationException("Unable to establish encryption"); return sslStream; }
/// <summary> Build a DProtocol object from a the given socket connection.</summary> internal static DProtocol createFromSocket(System.Net.Sockets.TcpClient s) { // For performance reasons, it is very important that we setTcpNoDelay(true), // thus disabling Nagle's algorithm. Google for TCP_NODELAY or Nagle // for more information. // // In addition, we now use a BufferedOutputStream instead of an OutputStream. // // These changes result in a huge speedup on the Mac. s.NoDelay = true; // We need to make sure that the socket is in blocking mode or BufferedStream // gets confused and screws up. s.ReceiveTimeout = 0; BufferedStream inStream = new BufferedStream(s.GetStream()); BufferedStream outStream = new BufferedStream(s.GetStream()); DProtocol dp = new DProtocol(inStream, outStream); return dp; }
static void HandleConnection(string modeName, Guid chatServiceAnouncementType, System.Net.Sockets.TcpClient TC) { if (modeName == null) throw new ArgumentNullException ("modeName"); if (TC == null) throw new ArgumentNullException ("TC"); System.IO.Stream PS = TC.GetStream (); StreamHandler SH = new StreamHandler (PS); ObjectBus OB = new ObjectBus (SH); ServiceManager SM = new ServiceManager (OB); if (modeName == "Server") { SM.AnnounceService (new ServiceAnnounceMessage (Guid.NewGuid (), chatServiceAnouncementType, "Chat", null), StreamPairAgent.CreateAgent); SM.AnounceReady (); } if (modeName == "Client") { SM.WaitForRemoteReady (); foreach (ServiceAnnounceMessage RSA in SM.EnumerateRemoteServices ()) { Console.WriteLine ("Service found: {0}", RSA.Name); SM.RequestService (RSA, null, StreamPairAgent.CreateAgent, null); } } }
static void HandleConnection(string modeName, Guid fileShareServiceAnouncementType, System.Net.Sockets.TcpClient TC) { if (modeName == null) throw new ArgumentNullException ("modeName"); if (TC == null) throw new ArgumentNullException ("TC"); System.IO.Stream PS = TC.GetStream (); StreamHandler SH = new StreamHandler (PS); ObjectBus OB = new ObjectBus (SH); ServiceManager SM = new ServiceManager (OB); if (modeName == "Server") { SM.AnnounceService (new ServiceAnnounceMessage (Guid.NewGuid (), fileShareServiceAnouncementType, "FileShare", null), FileShareAgent.CreateAgent); } if (modeName == "Client") { foreach (ServiceAnnounceMessage RSA in SM.EnumerateRemoteServices ()) { Console.WriteLine ("Service found: {0}", RSA.Name); Console.WriteLine ("Press Enter to request service"); ConsoleReadLine (); SM.RequestService (RSA, new byte[] { }, FileShareAgent.CreateAgent, new byte[] { }); } } }
/// <summary> Creates a new instance of Connection, with inbound communication on one /// port and outbound on another. /// </summary> public NuGenConnection(Parser parser, LowerLayerProtocol llp, System.Net.Sockets.TcpClient inbound, System.Net.Sockets.TcpClient outbound) { init(parser); ackWriter = llp.getWriter(inbound.GetStream()); sendWriter = llp.getWriter(outbound.GetStream()); sockets.Add(outbound); //always add outbound first ... see getRemoteAddress() sockets.Add(inbound); NuGenReceiver inRec = new NuGenReceiver(this, llp.getReader(inbound.GetStream())); NuGenReceiver outRec = new NuGenReceiver(this, llp.getReader(outbound.GetStream())); inRec.start(); outRec.start(); receivers.Add(inRec); receivers.Add(outRec); this.initiator = new NuGenInitiator(this); }
/*this method now throws exception if we don't get full read */ protected internal virtual int readSock(System.Net.Sockets.TcpClient s, byte[] b) { int got = 0; int len = (int) (b.Length); int i; System.IO.Stream is_Renamed = null; lock (this) { if (s == null) { throw new System.IO.IOException("expected " + len + " bytes, socket was closed"); } is_Renamed = (System.IO.Stream)s.GetStream(); } while (got < len && is_Renamed.CanRead) { i = is_Renamed.Read(b, got, len - got); if (i < 0) { throw new System.IO.IOException("Expected " + len + " bytes, got EOF after " + got + " bytes"); } else if (i == 0) { throw new System.IO.IOException("Remote connection closed"); } else got += i; } return got; }
/*this method now throws exception if we don't get full read */ protected internal virtual int readSock(System.Net.Sockets.TcpClient s, byte[] b, int sz, bool readingPayload) { int got = 0; int len = sz; int i; System.IO.Stream is_Renamed = null; lock (this) { if (s == null) { throw new System.IO.IOException("expected " + len + " bytes, socket was closed"); } is_Renamed = (System.IO.Stream)s.GetStream(); } while (got < len && is_Renamed.CanRead) { i = is_Renamed.Read(b, got, len - got); if (i < 0) { throw new System.IO.IOException("Expected " + len + " bytes, got EOF after " + got + " bytes"); } else if (i == 0) { throw new System.IO.IOException("Remote connection closed"); } got += i; } receivedBytes += got; if (readingPayload) { receivedMsgs++; if (onReadWrite != null) onReadWrite(this, Operation.Read, got + 4 /* header len */, receivedBytes, receivedMsgs); } return got; }
Connection(System.Net.Sockets.TcpClient client) : this(client.GetStream()) { this.client = client; this.client.NoDelay = true; }
public static System.IO.UnmanagedMemoryStream Find(string name, System.Resources.ResourceManager resManager, System.Globalization.CultureInfo culture) { return resManager.GetStream(name, culture); }
/// <summary> /// Allows customization of the connection handshake (SSL) /// </summary> protected virtual Stream ConnectServer(System.Net.Sockets.TcpClient client) { return client.GetStream(); }
/// <summary> Creates a new instance of Connection, with inbound and outbound /// communication on a single port. /// </summary> public NuGenConnection(Parser parser, LowerLayerProtocol llp, System.Net.Sockets.TcpClient bidirectional) { init(parser); ackWriter = llp.getWriter(bidirectional.GetStream()); sendWriter = ackWriter; sockets.Add(bidirectional); NuGenReceiver r = new NuGenReceiver(this, llp.getReader(bidirectional.GetStream())); r.start(); receivers.Add(r); this.initiator = new NuGenInitiator(this); }
/// <summary> /// Ein neuer Kommand ist über eine Kommunikationsschnittstelle angekommen /// kümmern wir uns darum! /// </summary> /// <param name="client"></param> /// <param name="Command"></param> public virtual void CommandRecieved(System.Net.Sockets.TcpClient client, Commands.BaseCommand recievedCommand) { Console.WriteLine(recievedCommand.GetType().ToString()); try{ if (recievedCommand.completed) { recievedCommand.ProcessResults(this); if (!recievedCommand.isAsync) { lock (SynclockCommands) { SyncCommands.Add(recievedCommand.guid, recievedCommand); } } } else { Console.WriteLine("RemoteExec"); recievedCommand.RemoteExecute(this); recievedCommand.completed = true; BinaryFormatter formatter = new BinaryFormatter(); MemoryStream memstr = new MemoryStream(); formatter.Serialize(memstr, recievedCommand); var outputstream = client.GetStream(); outputstream.Write(memstr.ToArray(),0,Convert.ToInt32(memstr.Length)); outputstream.Flush(); } }catch (Exception ex){ Console.WriteLine(ex.Message+ " "+ ex.StackTrace.ToString()); } }