public MobileTcpRemoteClient(RemotePoint point, ITcpSocketClient client) { _client = client; RemotePoint = point; ReadStream = client.ReadStream; WriteStream = client.WriteStream; }
/// <summary> /// Initializes a new instance of the <see cref="FtpConnection"/> class. /// </summary> /// <param name="server">The server this connection belongs to</param> /// <param name="socket">The socket to use to communicate with the client</param> /// <param name="encoding">The encoding to use for the LIST/NLST commands</param> public FtpConnection([NotNull] FtpServer server, [NotNull] ITcpSocketClient socket, [NotNull] Encoding encoding) { Server = server; _socket = socket; RemoteAddress = new Address(socket.RemoteAddress, socket.RemotePort); SocketStream = OriginalStream = socket.GetStream(); Encoding = encoding; Data = new FtpConnectionData(this); var commandHandlers = Server.CommandsHandlerFactory.CreateCommandHandlers(this).ToList(); CommandHandlers = commandHandlers .SelectMany(x => x.Names, (item, name) => new { Name = name, Item = item }) .ToDictionary(x => x.Name, x => x.Item, StringComparer.OrdinalIgnoreCase); // Add stand-alone extensions AddExtensions(Server.CommandsHandlerFactory.CreateCommandHandlerExtensions(this)); // Add extensions provided by command handlers foreach (var commandHandler in commandHandlers) AddExtensions(commandHandler.GetExtensions()); }
public JsonProtocolMessenger(ITcpSocketClient client) { _client = client; _messageSubject = new Subject <TMessage>(); }
private static void HandleMessage(ITcpSocketClient sender, ResponseRequest e) { var user = e.Data.ChangeType <User>(); Console.WriteLine(sender.RemoteAddress + ":" + sender.RemotePort + "\t\tSaid: " + user.ToString()); }
// For testing only internal SocketClient(IMessageReader reader, IMessageWriter writer, ITcpSocketClient socketClient = null) { Reader = reader; Writer = writer; _tcpSocketClient = socketClient; }
public SocketClient(Uri uri, EncryptionManager encryptionManager, ILogger logger, ITcpSocketClient socketClient = null) { if (uri != null && uri.Scheme.ToLowerInvariant() != Scheme) { throw new NotSupportedException($"Unsupported protocol: {uri.Scheme}"); } _uri = uri; _encryptionManager = encryptionManager; _logger = logger; _tcpSocketClient = socketClient ?? new TcpSocketClient(_encryptionManager); }
public void NotifyClient(ITcpSocketClient client, string message) { this.Send(client, message.ToByteArray()); }
/// <summary> /// Constructor for <code>TcpSocketListenerConnectEventArgs.</code> /// </summary> /// <param name="socketClient">A <code>TcpSocketClient</code> representing the newly connected client.</param> public TcpSocketListenerConnectEventArgs(ITcpSocketClient socketClient) { _socketClient = socketClient; }
private async void ProcessRequestAsync(ITcpSocketClient socket) { // this works for text only StringBuilder request = new StringBuilder(); byte[] data = new byte[BufferSize]; int byteread = BufferSize; bool error = false; while (byteread == BufferSize) { try { byteread = await socket.ReadStream.ReadAsync(data, 0, BufferSize); request.Append(Encoding.UTF8.GetString(data, 0, byteread)); } catch (Exception ex) { _2BDebug.Output(ex); error = true; break; } } if (!error && request.ToString().Length > 0) { string requestMethod = request.ToString().Split('\n')[0]; string[] requestParts = requestMethod.Split(' '); string requestPart = string.Empty; Debug.WriteLine(requestMethod); if (requestParts[0] == "GET" && requestParts.Count() > 1) { requestPart = requestParts[1]; } if (requestPart != string.Empty) await WriteResponseAsync(requestPart, socket); } try { socket.Dispose(); } catch (Exception ex) { _2BDebug.Output(ex); } }
private async Task WriteResponseAsync(string request, ITcpSocketClient socket ) { Stream writeStream = socket.WriteStream; IGWClient client = null; Dictionary<string, string> parameters = null; const string C_REPTYPE = "reptype"; const string C_CONTENTTYPE_HTML = "text/html; charset=utf-8;"; const string C_REPTYPE_XML = "xml"; const string C_CONTENTTYPE_XML = "text/xml; charset=utf-8;"; #if JSON const string C_REPTYPE_JSON = "json"; const string C_CONTENTTYPE_JSON = "application/json"; #endif const string C_HTTP_CODE_OK = "200"; const string C_HTTP_CODE_BADREQUEST = "400"; const string C_HTTP_CODE_NOTFOUND = "404"; const string C_HTTP_CODE_INTERNAL_ERROR = "500"; string httpCode = C_HTTP_CODE_OK; string httpCodeTest = ""; string httpContent = ""; string httpContentType = C_CONTENTTYPE_XML; // default XML // parse request to get client and parametres items RequestParse(request, out client, out parameters); if (client != null) { // check response format to use if (parameters != null && parameters.ContainsKey(C_REPTYPE)) { if (parameters[C_REPTYPE] == C_REPTYPE_XML) httpContentType = C_CONTENTTYPE_XML; #if JSON else if (parameters[C_REPTYPE] == C_REPTYPE_JSON) httpContentType = C_CONTENTTYPE_JSON; #endif else { client = null; // bad => simulate 400 httpCode = C_HTTP_CODE_BADREQUEST; } } } else { httpCode = C_HTTP_CODE_NOTFOUND; } if (client != null) { // transfert request to client GWClientResult ret = await client.ExecuteAsync(parameters); if (ret!= null) { // contruct response XElement xresult = new XElement("Result"); XElement xrequest = new XElement("Request"); XElement xresponse = new XElement("Response"); xrequest.Add(new XElement("Uri", request)); xrequest.Add(new XElement("RemoteAddress", socket.RemoteAddress)); xrequest.Add(new XElement("RemotePort", socket.RemotePort)); XElement xparams = new XElement("Parameters"); if (parameters != null) { foreach (var parmeter in parameters) { XElement xparam = new XElement("Parameter"); xparam.Add(new XAttribute("Key", parmeter.Key)); xparam.Add(new XElement("Value", parmeter.Value)); xparams.Add(xparam); } } xrequest.Add(xparams); xresponse.Add(new XElement("Success", ret.Success ? "1" : "0")); xresponse.Add(new XElement("Message", ret.Message)); xresponse.Add(ret.Data); xresult.Add(xrequest); xresult.Add(xresponse); ret.Data.Add(new XAttribute("ClientName", client.Name)); if (httpContentType == C_CONTENTTYPE_XML) { XDeclaration decl = new XDeclaration("1.0", "UTF-8", null); httpContent = decl.ToString() + "\r\n" + xresult.ToString(); } #if JSON else if (httpContentType == C_CONTENTTYPE_JSON) { httpContent = JsonConvert.SerializeObject(xresult); } #endif } else { client = null; httpCode = C_HTTP_CODE_INTERNAL_ERROR; } } // bad request or client not found if (client == null) { switch (httpCode) { case C_HTTP_CODE_BADREQUEST: httpCodeTest = "BAD RESQUEST"; break; case C_HTTP_CODE_NOTFOUND: httpCodeTest = "NOT FOUND"; break; case C_HTTP_CODE_INTERNAL_ERROR: httpCodeTest = "INTERNAL SERVER ERROR"; break; default: httpCodeTest = "UNKNWON CODE"; break; } httpContentType = C_CONTENTTYPE_HTML; httpContent = string.Format("<html><body>{0} - {1} : {2}</body></html>", httpCode, httpCodeTest, request); } // write response byte[] bodyArray = Encoding.UTF8.GetBytes(httpContent); string header = String.Format("HTTP/1.1 {0} OK\r\n" + "Content-Length: {1}\r\n" + "Content-Type: {2} \r\n" + "Connection: close\r\n\r\n", httpCode, bodyArray.Length, httpContentType); byte[] headerArray = Encoding.UTF8.GetBytes(header); try { await writeStream.WriteAsync(headerArray, 0, headerArray.Length); if (bodyArray.Length > 0) { await writeStream.WriteAsync(bodyArray, 0, bodyArray.Length); } await writeStream.FlushAsync(); } catch (Exception ex) { _2BDebug.Output(ex); } }
internal IObservable <string> CreateObservableListener( CancellationTokenSource innerCancellationTokenSource, ITcpSocketClient tcpSocketClient, IEnumerable <string> subProtocols = null) { var parserDelegate = new HttpParserDelegate(); var parserHandler = new HttpCombinedParser(parserDelegate); TextDataParser.Reinitialize(); _innerCancellationTokenSource = innerCancellationTokenSource; _tcpSocketClient = tcpSocketClient; DataReceiveMode = DataReceiveMode.IsListeningForHandShake; IsConnected = false; _isHandshaking = true; WatchHandshakeForTimeout(parserDelegate, _innerCancellationTokenSource); var observable = Observable.Create <string>( obs => { var disp = _tcpSocketClient.ReadStream.ReadOneByteAtTheTimeObservable(innerCancellationTokenSource, isConnectionOpen: IsConnected || _isHandshaking) .Subscribe( b => { if (TextDataParser.IsCloseRecieved) { return; } if (_hasHandshakeTimedout) { _subjectConnectionStatus.OnNext(ConnectionStatus.Aborted); throw new WebsocketClientLiteException("Connection request to server timed out"); } switch (DataReceiveMode) { case DataReceiveMode.IsListeningForHandShake: _handshakeParser.Parse(b, parserDelegate, parserHandler); HandshakeController(parserDelegate, subProtocols); break; case DataReceiveMode.IsListeningForTextData: TextDataParser.Parse(_tcpSocketClient, b[0], ExcludeZeroApplicationDataInPong); if (TextDataParser.IsCloseRecieved) { StopReceivingData(); } if (TextDataParser.HasNewMessage) { obs.OnNext(TextDataParser.NewMessage); } break; } }, ex => { StopReceivingData(); throw ex; }, () => { // ReSharper disable once ConvertClosureToMethodGroup StopReceivingData(); } ); HasReceivedCloseFromServer = false; return(disp); }); return(observable); }
public SocketClient(Uri uri, EncryptionManager encryptionManager, bool socketKeepAlive, bool ipv6Enabled, ILogger logger, ITcpSocketClient socketClient = null) { _uri = uri; _logger = logger; _tcpSocketClient = socketClient ?? new TcpSocketClient(encryptionManager, socketKeepAlive, ipv6Enabled, _logger); }
// For testing only internal SocketClient(IBoltProtocol boltProtocol, ITcpSocketClient socketClient = null) { _boltProtocol = boltProtocol; _tcpSocketClient = socketClient; }
public SocketClient(Uri uri, SocketSettings socketSettings, BufferSettings bufferSettings, IConnectionListener connMetricsListener = null, ILogger logger = null, ITcpSocketClient socketClient = null) { _uri = uri; _logger = logger; _bufferSettings = bufferSettings; _tcpSocketClient = socketClient ?? new TcpSocketClient(socketSettings, _logger); _connMetricsListener = connMetricsListener; if (_connMetricsListener != null) { _connEvent = new SimpleTimerEvent(); } }
/// <summary> /// Wraps <see cref="ITcpSocketClient.ReadStream"/> and <see cref="ITcpSocketClient.WriteStream"/> into /// a single <see cref="System.IO.Stream"/>. This is primarily intended for migrations from existing code /// that uses <see cref="System.Net.TcpClient.GetStream"/>. /// </summary> /// <param name="client"> /// The instance of <see cref="ITcpSocketClient"/> /// </param> /// <returns> /// A single stream that wraps <see cref="ITcpSocketClient.ReadStream"/> and /// <see cref="ITcpSocketClient.WriteStream"/>. /// </returns> public static Stream GetStream(this ITcpSocketClient client) { Contract.Requires(client != null); return(new TwoWayStream(client.ReadStream, client.WriteStream)); }
public PackStreamMessageFormatV1(ITcpSocketClient tcpSocketClient, ILogger logger) { Writer = new WriterV1(new ChunkedOutputStream(tcpSocketClient, logger)); Reader = new ReaderV1(new ChunkedInputStream(tcpSocketClient, logger)); }
/// <summary> /// Listeners the connection. /// </summary> /// <param name="s">S.</param> /// <param name="e">E.</param> public void ListenerConnection(Object s, EventArgs e) { bool disconnected = false; var listener = new TcpSocketListener(); Listener_Rady.Text = "接続待機中"; Listener_Rady.TextColor = Color.Blue; // ホスト名を取得する var TcpLocator = DependencyService.Get <IGeolocator>(); Listener_Disp.Text = TcpLocator.getIPAddress(); // when we get connections, read bytes until we get -1 (eof) listener.ConnectionReceived += async(sender, args) => { //サーバー用ソケットの取得 serverSocket = /*(Sockets.Plugin.TcpSocketClient)*/ args.SocketClient;//*/ GetSocketClient(args); string Adress = args.SocketClient.RemoteAddress; var port = args.SocketClient.RemotePort; var bytesRead = -1; var buf = new byte[1024]; // read from the 'ReadStream' property of the socket client to receive data bytesRead = await args.SocketClient.ReadStream.ReadAsync(buf, 0, buf.Length); //受信したデータを文字列に変換 Encoding enc = System.Text.Encoding.UTF8; string resMsg = enc.GetString(buf, 0, bytesRead); //末尾の\nを削除 resMsg = resMsg.TrimEnd('\n'); if (resMsg == "+OK to BondotConnectio!" | disconnected == false)// ID Check { string listenerMsg = string.Format("クライアントに接続しました IpAdress{0} Port {1}" + '\n', Adress, port); Device.BeginInvokeOnMainThread(() => { DisplayAlert("For listener Message ", listenerMsg, "OK"); Listener_Rady.Text = "接続中"; Listener_Rady.TextColor = Color.Red; Listener_Send.IsEnabled = true; }); //クライアントに接続応答する //NetworkStreamを取得 System.IO.Stream writer = serverSocket.GetStream(); //クライアントに送信する文字列を作成 string sendMsg = resMsg; //文字列をByte型配列に変換 byte[] sendBytes = enc.GetBytes(sendMsg + "listener-Anser" + '\n'); //データを送信する writer.Write(sendBytes, 0, sendBytes.Length); disconnected = true; } else { Device.BeginInvokeOnMainThread(() => { Listener_Disp.Text = resMsg; DisplayAlert("For Client Message ", resMsg, "OK"); }); } //閉じる // ns.Dispose(); // serverSocket.Dispose(); }; //IPアドレスとポートをバインドして接続待機 /// bind to the listen port across all interfaces listener.StartListeningAsync(Port); }
internal async Task SendTextAsync(ITcpSocketClient tcpSocketClient, string message) { var msgAsBytes = Encoding.UTF8.GetBytes(message); await ComposeFrameAsync(tcpSocketClient, msgAsBytes, FrameType.Single); }
public void NotifyClient(ITcpSocketClient client, ResponseRequest message) { this.Send(client, message.ToByteArray()); }
public ChunkedInputStream(ITcpSocketClient tcpSocketClient, ILogger logger, int?chunkSize = ChunkSize) { _tcpSocketClient = tcpSocketClient; _logger = logger; _chunkBuffer = new Queue <byte>(chunkSize.Value); }
/// <summary> /// Constructor for <code>TcpSocketListenerConnectEventArgs.</code> /// </summary> /// <param name="socketClient">A <code>TcpSocketClient</code> representing the newly connected client.</param> public TcpSocketListenerConnectEventArgs(ITcpSocketClient socketClient) { _socketClient = socketClient; }
public PackStreamMessageFormatV1(ITcpSocketClient tcpSocketClient, BitConverterBase bitConverter, ILogger logger) { _bitConverter = bitConverter; Writer = new WriterV1(new ChunkedOutputStream(tcpSocketClient, bitConverter, logger)); Reader = new ReaderV1(new ChunkedInputStream(tcpSocketClient, bitConverter, logger)); }
internal SocketClient(Uri uri, EncryptionManager encryptionManager, ITcpSocketClient socketClient) : this(uri, encryptionManager, null, socketClient) { }
public ConnectionHandler(ITcpSocketClient TcpSocketClient) { this.TcpSocketClient = TcpSocketClient; }
public SocketClient(Uri url, Config config, ITcpSocketClient socketClient = null) { _url = url; _config = config; _tcpSocketClient = socketClient ?? new TcpSocketClient(); }
private void SendPong(ITcpSocketClient tcpSocketClient) { Task.Run(async() => await SendPongAsync(tcpSocketClient)).ConfigureAwait(false); }