//public void Execute(Request request, // Tcp.Params.Buffer receiveBufferSettings, Tcp.Params.Buffer sendBufferSettings) //{ // Execute(request, receiveBufferSettings, sendBufferSettings); //} public void Execute(Request request, Tcp.Params.Buffer receiveBufferSettings, Tcp.Params.Buffer sendBufferSettings, HttpConnection.ConnectionDelegate onConnectCallback, HttpConnection.ConnectionDelegate onDisconnectCallback, HttpConnection.ErrorDelegate onErrorCallback, HttpConnection.ProgressDelegate onProgressCallback, HttpConnection.ConnectionDelegate onTimeoutCallback, HttpConnection.CompletionDelegate onCompleteCallback) { HttpConnection conn; conn = new HttpConnection(request.RequestLine.RequestUri, receiveBufferSettings, sendBufferSettings); if (onDisconnectCallback != null) conn.OnDisconnect += onDisconnectCallback; if (onErrorCallback != null) conn.OnError += onErrorCallback; if (onProgressCallback != null) conn.OnProgress += onProgressCallback; if (onTimeoutCallback != null) conn.OnTimeout += onTimeoutCallback; if (onCompleteCallback != null) conn.OnComplete += onCompleteCallback; conn.OnConnect += delegate(HttpConnection sender) { if (onConnectCallback != null) onConnectCallback(sender); conn.SendRequestAsync(request); }; conn.ConnectAsync(); }
private void TransciverOnRecived(Tcp.Connection connection, Transciver transciver, TcRxArgs args) { BaseConnection.Statistic.IsResponsive = true; _heartbeatTimer.Stop(); if (BaseConnection.IsOpened) _heartbeatTimer.Start(); }
public void ParseAndAttachToBody(Tcp.TcpConnection connection, AsyncCallback callback) { // We are not worrying about onProgress, onTimeout, onError because the developer should // already have those listeners attached connection.ReceiveAsync(ParseAndAttachToBody_Callback, callback); }
internal BlockingTcp(Tcp tcp) : base(tcp.Loop) { Handle = tcp; Stream = tcp; Tcp = tcp; }
public void Run() { _stepIndex = 0; _tcp = new Tcp(); _tcp.Listen(Port, ProcessClientRequest); Thread.Sleep(100); // let server start }
protected virtual void OnConnect(Tcp.Connection connection) { this.activeConnections.Add(connection); connection.Closed += () => this.activeConnections.Remove(c => connection == c); this.Connected(connection); if (connection.AutoClose) connection.Close(); }
public HttpConnection(Uri uri, Tcp.Params.Buffer receiveBufferSettings, Tcp.Params.Buffer sendBufferSettings) { Uri = uri; _receiveBufferSettings = receiveBufferSettings; _sendBufferSettings = sendBufferSettings; Logger.Network.Debug("HttpConnection ID: " + this.GetHashCode().ToString() + "\r\nHttpConnection created."); }
public void ConnectToNotListeningPort() { Tcp socket = new Tcp(); socket.Connect("127.0.0.1", 7999, (e) => { Assert.IsNotNull(e); }); Loop.Default.Run(); }
static void OnConnection(Tcp tcpClient, Exception error) { if (error != null) { Console.WriteLine($"Echo server client connection failed {error}"); tcpClient?.Dispose(); } else { Console.WriteLine($"Echo server client connection accepted {tcpClient.GetPeerEndPoint()}"); connections.Add(tcpClient); } }
static void SendMessage(Tcp tcp, Exception error) { if (error != null) { Console.WriteLine($"Echo client error {error}"); tcp.Dispose(); return; } Console.WriteLine("Echo client connected, request write message."); byte[] bytes = Encoding.UTF8.GetBytes($"Greetings {DateTime.UtcNow}"); tcp.QueueWrite(bytes, OnWriteCompleted); }
public void Dispose() { this.endPoint = null; this.tcp?.Dispose(); this.tcp = null; this.timer?.Dispose(); this.timer = null; this.loop?.Dispose(); this.loop = null; }
void OnWriteComplete(Tcp tcp, Exception error) { if (error != null) { Console.WriteLine($"tcp pump {this.clientCount} failed, {error}"); tcp.Dispose(); return; } this.totalBytesWrite += WriteBufferSize; this.bytesWrite += WriteBufferSize; this.Write(tcp); }
private void WithServerClient <T>(IEnumerable <IEndpoint <T> > endpoints, string path, Action <IWsServer <T>, JsonWsClient> action) { var serverPort = Tcp.FreePort(); using (var server = new MultiEndpointWsServer <T>(NullLogger.Instance, IPAddress.Any, serverPort, endpoints)) { server.Start(); using (var client = new JsonWsClient(Timeout, serverPort, path)) { action(server, client); } } }
public void Connect_Missing_TCP_Port() { var tcp = new Tcp(); ExceptionAssert.Throws <Exception>(() => { var _ = tcp.ConnectAsync("/ip4/127.0.0.1/udp/32700").Result; }); ExceptionAssert.Throws <Exception>(() => { var _ = tcp.ConnectAsync("/ip4/127.0.0.1").Result; }); }
public void Run() { Tcp tcp = this.loop.CreateTcp(); tcp.NoDelay(true); tcp.KeepAlive(true, 60); tcp.CloseHandle(OnClose); int result = this.loop.RunDefault(); Assert.Equal(0, result); }
public void TcpListen() { Tcp tcp = this.loop.CreateTcp(); var anyEndPoint = new IPEndPoint(IPAddress.Loopback, IPEndPoint.MinPort); tcp.Listen(anyEndPoint, this.OnConnection); tcp.RemoveReference(); this.loop.RunDefault(); Assert.Equal(0, this.callbackCount); tcp.CloseHandle(this.OnClose); }
void OnRead(Tcp tcp, IStreamReadCompletion completion) { if (completion.Error != null || completion.Completed) { tcp.CloseHandle(this.OnClose); this.server.CloseHandle(this.OnClose); } else { this.bytesRead += completion.Data.Count; } }
protected override void ParseAndAttachToBody_Callback(Tcp.TcpConnection sender, Tcp.TcpConnectionAsyncEventArgs e) { HttpNetworkStream ns; AsyncCallback callback = (AsyncCallback)e.UserToken; AppendAndParse(e.Buffer, 0, e.Length); if (AllHeadersReceived) { if (!Request.ContentLength.HasValue) throw new HttpNetworkStreamException("A Content-Length header was not found."); ulong temp = (ulong)Request.ContentLength.Value; if (_remainingBufferAppendPosition > 0) { // We need to take the left over buffer from _responseBuilder and prepend that // to an HttpNetworkStream wrapping the _tcpConnection and then give the user // that HttpNetworkStream... cake byte[] newBuffer = new byte[_remainingBufferAppendPosition]; BytesReceived += e.BytesTransferred - newBuffer.Length; MessageSize = BytesReceived + Request.ContentLength.Value; Buffer.BlockCopy(_remainingBuffer, 0, newBuffer, 0, newBuffer.Length); ns = new HttpNetworkStream(HttpNetworkStream.DirectionType.Upload, temp, newBuffer, sender.Socket, System.IO.FileAccess.Write, false); } else { BytesReceived += e.BytesTransferred; MessageSize = BytesReceived + Response.ContentLength.Value; ns = new HttpNetworkStream(HttpNetworkStream.DirectionType.Upload, temp, sender.Socket, System.IO.FileAccess.Write, false); } if (Request.Headers.ContainsKey(new Message.ChunkedTransferEncodingHeader())) Request.Body.IsChunked = true; Response.Body.ReceiveStream = ns; callback(this, Response); } else { BytesReceived += e.Length; sender.ReceiveAsync(ParseAndAttachToBody_Callback, callback); } }
public static void Simple(IPEndPoint ep) { int close_cb_called = 0; int cl_send_cb_called = 0; int cl_recv_cb_called = 0; int sv_send_cb_called = 0; int sv_recv_cb_called = 0; var server = new TcpListener(); server.Bind(ep); server.Listen((socket) => { socket.Resume(); socket.Read(Encoding.ASCII, (str) => { sv_recv_cb_called++; Assert.AreEqual("PING", str); socket.Write(Encoding.ASCII, "PONG", (s) => { sv_send_cb_called++; }); socket.Close(() => { close_cb_called++; }); server.Close(() => { close_cb_called++; }); }); }); Tcp.Connect(Loop.Default, ep, (_, client) => { client.Resume(); client.Write(Encoding.ASCII, "PING", (s) => { cl_send_cb_called++; }); client.Read(Encoding.ASCII, (str) => { cl_recv_cb_called++; Assert.AreEqual("PONG", str); client.Close(() => { close_cb_called++; }); }); }); Assert.AreEqual(0, close_cb_called); Assert.AreEqual(0, cl_send_cb_called); Assert.AreEqual(0, cl_recv_cb_called); Assert.AreEqual(0, sv_send_cb_called); Assert.AreEqual(0, sv_recv_cb_called); Loop.Default.Run(); Assert.AreEqual(3, close_cb_called); Assert.AreEqual(1, cl_send_cb_called); Assert.AreEqual(1, cl_recv_cb_called); Assert.AreEqual(1, sv_send_cb_called); Assert.AreEqual(1, sv_recv_cb_called); #if DEBUG Assert.AreEqual(1, UV.PointerCount); #endif }
private static void HelloToServer() { try { var vpsName = clientId.GetInfo("VpsClientId", "null"); var clientDeviceId = clientId.GetInfo("clientDeviceId", HttpUtil.UUID); clientId.SetInfo("clientDeviceId", clientDeviceId); Tcp?.Send(new RpClientConnectMessage("vps", Assembly.GetExecutingAssembly().GetName().Version.ToString(), clientDeviceId, vpsName)); } catch (Exception ex) { Console.WriteLine("HelloToServer()" + ex.Message); } }
public static void Init(Tcp tcp, Udp udp) { if (Instance == null) { Instance = new Client { Tcp = tcp, Udp = udp }; Instance.Udp.Init(Constants.Ip, Constants.Port); } else { Console.WriteLine("Instance already exists, destroying Object!"); } }
private static void MinerCallBack_CmdSynInit(ClientMessageEventArgs e) { var interval = e.Message["Interval"]; var assumePriceRate = e.Message["AssumePriceRate"]; if (interval == null || assumePriceRate == null) { Tcp.Send(new RpMsgInvalidMessage("synInit")); return; } InitSetting(Convert.ToInt32(interval), Convert.ToDouble(assumePriceRate)); Program.vpsStatus = VpsStatus.Syning; Tcp.Send(new RpInitCompletedMessage()); }
public async void RefreshPlayers() { while (true) { try { label5.Text = "Last Refresh: " + GetCurrentTime(); listBox1.Items.Clear(); listBox1.Items.Add("Refreshing User List."); Thread.Sleep(1000); NetworkStream s = Tcp.Connect(ip, port); Tcp.SendData($"cmd|{Crypto.EncryptStringAES("dudeIdkDecryptThisSheitLmAO", Variables.CachePassword)}|getPlayers|{GetCurrentTime()}", s); string[] data = Tcp.Recieve(s); if (data[0] == "false") { MessageBox.Show("Failed to connect with the server,\nReason: Bad Password!", "DRA Connection"); } else if (data[0] == "notStarted") { listBox1.Items.Clear(); listBox1.Items.Add("The server has not fully started!"); } else if (data[0] == "timeSkip") { listBox1.Items.Clear(); listBox1.Items.Add("Your time skipped! Retrying in 10s"); } else { string data2 = string.Join("\n", data); string[] data3 = data2.Split('\n'); listBox1.Items.Clear(); foreach (string strin in data3) { listBox1.Items.Add(strin); } } Thread.Sleep(10000); } catch { MessageBox.Show("Failed to connect!", "DRA Connection"); Application.Exit(); } } }
public static void Main(string[] args) { Loop.Default.Run(async() => { var tcp = new Tcp(); await tcp.ConnectAsync(Dns.GetHostAddressesAsync, "ip.bentkus.eu", 80); tcp.TryWrite("GET / HTTP/1.1\r\nHost: ip.bentkus.eu\r\n\r\n"); var data = await tcp.ReadStructAsync(); if (data.HasValue) { Console.WriteLine(Encoding.ASCII.GetString(data.Value.Array, data.Value.Offset, data.Value.Count)); } Console.WriteLine("Connected!"); }); }
void TestCanSendHandles(string pipename, IPEndPoint ipep) { int count = 0; Loop.Default.Run(async () => { var handles = new Stack<Handle>(); var pipelistener = new IPCPipeListener(); pipelistener.Bind(pipename); pipelistener.Connection += () => { var client = pipelistener.Accept(); client.Resume(); client.HandleData += (handle, data) => { handles.Push(handle); count++; if (count == 3) { foreach (var h in handles) { h.Close(); } pipelistener.Close(); } }; }; pipelistener.Listen(); var pipe = new IPCPipe(); await pipe.ConnectAsync(pipename); var tcplistener = new TcpListener(); tcplistener.Bind(ipep); tcplistener.Connection += () => { var client = tcplistener.Accept(); pipe.Write(client, new byte[1], (ex) => { client.Close(); tcplistener.Close(); }); }; tcplistener.Listen(); var tcp = new Tcp(); await tcp.ConnectAsync(ipep); tcp.Write("HELLO WORLD"); var udp = new Udp(); udp.Bind(ipep); pipe.Write(udp, Encoding.Default.GetBytes("UDP"), (ex) => udp.Close()); pipe.Write(pipe, Encoding.Default.GetBytes("pipe"), (ex) => pipe.Close()); }); Assert.Equal(3, count); }
public void Init(Loop loop, Tcp tcp, IComponentContext ctx, IPEndPoint endpointConfig, string connectionId) { Contract.RequiresNonNull(tcp, nameof(tcp)); Contract.RequiresNonNull(ctx, nameof(ctx)); Contract.RequiresNonNull(endpointConfig, nameof(endpointConfig)); PoolEndpoint = endpointConfig; // cached properties ConnectionId = connectionId; RemoteEndpoint = tcp.GetPeerEndPoint(); SetupConnection(loop, tcp); }
public void Init(IPEndPoint address, Action onConnected) { try { Close(); Tcp?.Dispose(); Tcp = new TcpClient(); Tcp.BeginConnect(address.Address, address.Port, e => onConnected(), null); Stream = Tcp.GetStream() as NetworkStream; Reader = new BinaryReader(Stream); Writer = new BinaryWriter(Stream); } catch { } }
public void TcpConnect2NoServer() { var endPoint = new IPEndPoint(IPAddress.Loopback, Port); Tcp tcp = this.loop .CreateTcp() .ConnectTo(endPoint, this.OnConnectedAndWrite); tcp.RemoveReference(); this.loop.RunDefault(); Assert.Equal(1, this.callbackCount); this.CloseHandle(tcp); }
void OnConnection(Tcp tcp, Exception exception) { this.connectionError = exception; this.connectionCount++; if (exception == null) { tcp.OnRead(this.OnRead); } else { tcp.CloseHandle(this.OnClose); } }
public void Dispose() { this.timer1.Dispose(); this.timer1 = null; this.timer2.Dispose(); this.timer2 = null; this.tcpClient.Dispose(); this.tcpClient = null; this.loop?.Dispose(); this.loop = null; }
void OnWriteCompleted(Tcp tcpClient, Exception error) { if (error == null) { return; } Console.WriteLine($"{nameof(EchoServer)} client connection failed, {error}"); tcpClient?.Dispose(); if (this.connections.Contains(tcpClient)) { this.connections.Remove(tcpClient); } }
public void Init(Tcp uvCon, IComponentContext ctx, IPEndPoint endpointConfig, string connectionId) { Contract.RequiresNonNull(uvCon, nameof(uvCon)); Contract.RequiresNonNull(ctx, nameof(ctx)); Contract.RequiresNonNull(endpointConfig, nameof(endpointConfig)); PoolEndpoint = endpointConfig; rpcCon = ctx.Resolve <JsonRpcConnection>(); rpcCon.Init(uvCon, connectionId); RemoteEndpoint = rpcCon.RemoteEndPoint; Requests = rpcCon.Received; }
private async Task ProcessMessage(NetworkStream stream, CancellationToken cancellation) { var messageSizeBytes = await Tcp.ReadFromStream(4, stream, cancellation).ConfigureAwait(true); var messageSize = (int)messageSizeBytes.AsLong(); var request = await Tcp.ReadFromStream(messageSize, stream, cancellation).ConfigureAwait(true); var response = await this.ProcessRequest(request, cancellation).ConfigureAwait(true); response = Tcp.FormatKerberosMessageStream(response); await stream.WriteAsync(response.ToArray(), 0, response.Length, cancellation).ConfigureAwait(true); }
public void Disconnect(TimeSpan timeout) { try { using (var tokenSource = new CancellationTokenSource(timeout)) { Transceiver.Stop(tokenSource.Token); } } catch {} try { Tcp.Close(); } catch {} }
public void TcpClose() { this.tcpServer = this.StartServer(); this.loop.CreateTcp().ConnectTo(this.endPoint, this.OnConnected); Assert.Equal(0, this.writeCount); Assert.Equal(0, this.closeCount); this.loop.RunDefault(); Assert.Equal(NumberOfWriteRequests, this.writeCount); Assert.Equal(1, this.closeCount); Assert.Null(this.writeError); Assert.Null(this.connectionError); }
void StartClient() { Tcp tcp = this.loop .CreateTcp() .ConnectTo(TestHelper.LoopbackEndPoint, this.OnConnected); this.startTime = this.loop.Now; this.loop.RunDefault(); long count = (long)Math.Floor((1000d * this.pongs) / DurationInMilliseconds); Console.WriteLine($"Tcp ping pong : {TestHelper.Format(count)} roundtrips/s"); tcp.Dispose(); }
void OnConnected(Tcp tcp, Exception error) { if (error != null) { Console.WriteLine($"Tcp ping pong : client connection failed, error {error}."); tcp.CloseHandle(OnClose); } else { tcp.OnRead(this.OnAccept, OnError); // Sending the first ping tcp.QueueWrite(this.content, OnWriteCompleted); } }
static void SetReuseAddress(Tcp tcp, int value) { try { PlatformApi.SetReuseAddress(tcp, value); } catch (ObjectDisposedException ex) { ThrowHelper.ThrowChannelException(ex); } catch (SocketException ex) { ThrowHelper.ThrowChannelException(ex); } }
static void SetKeepAlive(Tcp tcpHandle, int value) { try { tcpHandle.KeepAlive(value, 1 /* Delay in seconds to take effect*/); } catch (ObjectDisposedException ex) { ThrowHelper.ThrowChannelException(ex); } catch (OperationException ex) { ThrowHelper.ThrowChannelException(ex); } }
public void Invalid() { IPAddress address = IPAddress.Loopback; var endPoint1 = new IPEndPoint(address, Port); var endPoint2 = new IPEndPoint(address, Port + 1); Tcp tcp = this.loop.CreateTcp(); Assert.Equal(tcp.Bind(endPoint1), tcp); Assert.Throws <OperationException>(() => tcp.Bind(endPoint2)); tcp.CloseHandle(this.OnClose); this.loop.RunDefault(); Assert.Equal(1, this.closeCalled); }
public TcpOutgoingConnection(TcpExt tcp, IChannelRegistry channelRegistry, IActorRef commander, Tcp.Connect connect) : base(tcp, SocketChannel.Open().ConfigureBlocking(false), connect.PullMode) { _channelRegistry = channelRegistry; _commander = commander; _connect = connect; Context.Watch(commander); // sign death pact connect.Options.ForEach(_ => _.BeforeConnect(Channel.Socket)); if (connect.LocalAddress != null) Channel.Socket.Bind(connect.LocalAddress); channelRegistry.Register(Channel, SocketAsyncOperation.None, Self); if (connect.Timeout.HasValue) Context.SetReceiveTimeout(connect.Timeout.Value); //Initiate connection timeout if supplied }
public void Connect(IPEndPoint ep) { var thread = Thread; Exception ex = null; Tcp.Connect(Loop, ep, (exception, tcp) => { if (exception != null) { ex = exception; } else { Handle = tcp; Stream = tcp; Tcp = tcp; } thread.Resume(); }); thread.Yield(MicroThreadState.Blocking); if (ex != null) { throw ex; } }
public void RemoteAndLocalAddress() { Tcp client = null; Tcp server = null; bool called = false; var l = new TcpListener(); l.Bind(IPAddress.Any, 8000); Action check = () => { if (client == null || server == null) { return; } Assert.Equal(client.LocalAddress, server.RemoteAddress); Assert.Equal(client.RemoteAddress, server.LocalAddress); Assert.Equal(server.LocalAddress.Port, 8000); client.Shutdown(); server.Shutdown(); l.Close(); called = true; }; l.Listen(); l.Connection += () => { server = l.Accept(); check(); }; Tcp t = new Tcp(); t.Connect("127.0.0.1", 8000, (e) => { client = t; check(); }); Loop.Default.Run(); Assert.True(called); }
internal Transciver(Tcp.Connection @base) { _base = @base; }
private void ConnectAsync_OnHostResolved_OnError(Tcp.TcpConnection sender2, string message, Exception exception) { _tcpConnection.OnDisconnect -= ConnectAsync_OnHostResolved_OnDisconnect; _tcpConnection.OnConnect -= ConnectAsync_OnHostResolved_OnConnect; _tcpConnection.OnError -= ConnectAsync_OnHostResolved_OnError; _tcpConnection.OnTimeout -= ConnectAsync_OnHostResolved_OnTimeout; Logger.Network.Error("HttpConnection ID: " + this.GetHashCode().ToString() + "\r\nTcpConnection ID: " + _tcpConnection.GetHashCode().ToString() + "\r\nHttpConnection encountered an error.\r\nMessage: " + message, exception); if (OnError != null) OnError(this, message, exception); }
internal void ServiceFailed(ServiceFailedArgs.Regions region, Tcp.Service service, Exception exc) { ServiceFailedArgs args = new ServiceFailedArgs() { Region = region, Exception = exc, ServiceName = service.Name, ServiceNumber = service.Number }; BaseConnection.Log(service, args.ToString()); if (BaseConnection.IsOpened) { ServiceSend(args, Guid.Empty, 502); } }
private void ConnectAsync_OnHostResolved_OnTimeout(Tcp.TcpConnection sender) { _tcpConnection.OnDisconnect -= ConnectAsync_OnHostResolved_OnDisconnect; _tcpConnection.OnConnect -= ConnectAsync_OnHostResolved_OnConnect; _tcpConnection.OnError -= ConnectAsync_OnHostResolved_OnError; _tcpConnection.OnTimeout -= ConnectAsync_OnHostResolved_OnTimeout; Logger.Network.Debug("HttpConnection ID: " + this.GetHashCode().ToString() + "\r\nTcpConnection ID: " + _tcpConnection.GetHashCode().ToString() + "\r\nHttpConnection connected to remote host."); if (OnTimeout != null) OnTimeout(this); }
/// <summary> /// 设置TCP服务端 /// </summary> /// <param name="tcpServer">TCP服务端</param> public void SetTcpServer(Tcp.TmphServer tcpServer) { server = tcpServer; fileWatcher = new TmphCreateFlieTimeoutWatcher(TmphProcessCopy.Default.CheckTimeoutSeconds, onFileWatcherTimeout, TmphProcessCopyServer.DefaultFileWatcherFilter); if (!Config.TmphPub.Default.IsService && TmphProcessCopy.Default.WatcherPath != null) { try { fileWatcher.Add(TmphProcessCopy.Default.WatcherPath); } catch (Exception error) { TmphLog.Error.Add(error, TmphProcessCopy.Default.WatcherPath, false); } } if (IsLoadCache) { try { var cacheFileName = this.cacheFileName; if (File.Exists(cacheFileName)) { TmphInterlocked.NoCheckCompareSetSleep0(ref loadCacheLock); try { if (!IsLoadedCache) { var saveInfo = TmphDataDeSerializer.DeSerialize<TmphSaveInfo>(File.ReadAllBytes(cacheFileName)); if (saveInfo.ForwardHost.Port != 0) setForward(saveInfo.ForwardHost); if (saveInfo.Domains.length() != 0) { foreach (var domain in saveInfo.Domains) { try { start(domain.AssemblyPath, domain.ServerType, domain.Domains, domain.IsShareAssembly); } catch (Exception error) { TmphLog.Error.Add(error, null, false); } } } IsLoadedCache = true; } } finally { loadCacheLock = 0; } } } catch (Exception error) { TmphLog.Error.Add(error, null, false); } } }
public void ExpectClosed(Tcp.ConnectionClosed expected) => ExpectClosed(close => close == expected);
private void DisconnectAsync_OnError(Tcp.TcpConnection sender2, string message, Exception exception) { _tcpConnection.OnDisconnect -= DisconnectAsync_OnDisconnect; _tcpConnection.OnError -= DisconnectAsync_OnError; Logger.Network.Error("HttpConnection ID: " + this.GetHashCode().ToString() + "\r\nTcpConnection ID: " + _tcpConnection.GetHashCode().ToString() + "\r\nHttpConnection encountered an error while disconnecting from remote host\r\nMessage: " + message, exception); if (OnError != null) OnError(this, message, exception); }
private void SendRequest_OnTimeout(Tcp.TcpConnection sender) { _tcpConnection.OnError -= SendRequest_OnError; _tcpConnection.OnTimeout -= SendRequest_OnTimeout; Logger.Network.Error("HttpConnection ID: " + this.GetHashCode().ToString() + "\r\nTcpConnection ID: " + _tcpConnection.GetHashCode().ToString() + "\r\nHttpConnection send timed-out."); if (OnTimeout != null) OnTimeout(this); }
private void Check100Continue(Tcp.TcpConnection.AsyncCallback callback) { if (!IsConnected) throw new HttpConnectionException("A network connection is not established."); int loop = 0; // Loops every 0.25 seconds until either data is available or the receive timeout elapses while (_tcpConnection.BytesAvailable <= 0) { if ((_receiveBufferSettings.Timeout / 250) <= loop) { Logger.Network.Error("HttpConnection ID: " + this.GetHashCode().ToString() + "\r\nTcpConnection ID: " + _tcpConnection.GetHashCode().ToString() + "\r\nHttpConnection timed-out while waiting for the 100-Continue response from the remote server."); throw new TimeoutException("Timeout waiting for 100 continue status."); } System.Threading.Thread.Sleep(250); } _tcpConnection.ReceiveAsync(callback); }
public TestTcpOutgoingConnection(TcpExt tcp, IChannelRegistry channelRegistry, IActorRef commander, Tcp.Connect connect) : base(tcp, channelRegistry, commander, connect) { }
public Tcp.Write WriteCmd(Tcp.Event ack) { return Tcp.Write.Create(ByteString.Create(new byte[TestSize]), ack); }
private void ReceiveResponseAsync_OnTimeout(Tcp.TcpConnection sender) { _tcpConnection.OnError -= ReceiveResponseAsync_OnError; _tcpConnection.OnTimeout -= ReceiveResponseAsync_OnTimeout; Logger.Network.Debug("HttpConnection ID: " + this.GetHashCode().ToString() + "\r\nTcpConnection ID: " + _tcpConnection.GetHashCode().ToString() + "\r\nHttpConnection receiving of data timed-out."); if (OnTimeout != null) OnTimeout(this); }
protected override void ParseAndAttachToBody_Callback(Tcp.TcpConnection sender, Tcp.TcpConnectionAsyncEventArgs e) { HttpNetworkStream ns; byte[] newBuffer = null; AsyncCallback callback = (AsyncCallback)e.UserToken; AppendAndParse(e.Buffer, 0, e.BytesTransferred); if (AllHeadersReceived) { // Sets up the buffer to prepend if (_remainingBufferAppendPosition > 0) { // We need to take the left over buffer from _responseBuilder and prepend that // to an HttpNetworkStream wrapping the _tcpConnection and then give the user // that HttpNetworkStream... cake newBuffer = new byte[_remainingBufferAppendPosition]; BytesReceived += e.BytesTransferred - newBuffer.Length; Buffer.BlockCopy(_remainingBuffer, 0, newBuffer, 0, newBuffer.Length); } else { newBuffer = null; } if (!Response.ContentLength.HasValue) { // If content length is not set if (!Response.Headers.ContainsKey(new Message.ChunkedTransferEncodingHeader())) { throw new HttpNetworkStreamException("A Content-Length header was not found."); } MessageSize = 0; // NetworkStream needs modified to handle undetermined length ns = new HttpNetworkStream(HttpNetworkStream.DirectionType.Download, newBuffer, sender.Socket, System.IO.FileAccess.Read, false); Response.Body.IsChunked = true; Response.Body.ReceiveStream = new Interceptors.InterceptorStream(new Interceptors.ChunkedEncodingInterceptor(ns)); } else { // Content length is set if (Response.Headers.ContainsKey(new Message.ChunkedTransferEncodingHeader())) { throw new HttpNetworkStreamException("A Content-Length header was found in a chunked transfer."); } ulong temp = (ulong)Response.ContentLength.Value; MessageSize = BytesReceived + Response.ContentLength.Value; ns = new HttpNetworkStream(HttpNetworkStream.DirectionType.Download, temp, newBuffer, sender.Socket, System.IO.FileAccess.Read, false); Response.Body.ReceiveStream = ns; } callback(this, Response); } else { BytesReceived += e.BytesTransferred; sender.ReceiveAsync(ParseAndAttachToBody_Callback, callback); } }
internal Rx(Tcp.Connection @base) { _base = @base; }
private void DisconnectAsync_OnDisconnect(Tcp.TcpConnection sender2) { _tcpConnection.OnDisconnect -= DisconnectAsync_OnDisconnect; _tcpConnection.OnError -= DisconnectAsync_OnError; Logger.Network.Debug("HttpConnection ID: " + this.GetHashCode().ToString() + "\r\nTcpConnection ID: " + _tcpConnection.GetHashCode().ToString() + "\r\nHttpConnection disconnected from remote host."); if (OnDisconnect != null) OnDisconnect(this); }
public ClientClose(Tcp.CloseCommand cmd) { Cmd = cmd; }
private void ReceiveResponseAsync_OnError(Tcp.TcpConnection sender, string message, Exception exception) { _tcpConnection.OnError -= ReceiveResponseAsync_OnError; _tcpConnection.OnTimeout -= ReceiveResponseAsync_OnTimeout; Logger.Network.Debug("HttpConnection ID: " + this.GetHashCode().ToString() + "\r\nTcpConnection ID: " + _tcpConnection.GetHashCode().ToString() + "\r\nHttpConnection encountered an error receiving data\r\nMessage: " + message, exception); if (OnError != null) OnError(this, message, exception); }