private void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { if ((m_handler != null) && m_running) { IAsyncAction asyncAction = ThreadPool.RunAsync((workItem) => { StreamSocket s = args.Socket; try { m_handler( this, s.Information.RemoteHostName.CanonicalName.ToString(), s.InputStream.AsStreamForRead(), s.OutputStream.AsStreamForWrite() ); } catch (Exception) { // Quietly consume the exception } // Close the client socket s.Dispose(); }); } }
private async void ProcessRequestAsync(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { await Task.Run(async () => { try { using (var inputStream = args.Socket.InputStream) { var request = await HttpServerRequest.Parse(inputStream); var httpResponse = await HandleRequest(request); await WriteResponseAsync(httpResponse, args.Socket); } } catch (Exception ex) { Debug.WriteLine($"Exception while handling process: {ex.Message}"); } finally { try { args.Socket.Dispose(); } catch { } } }); }
private void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { if (this.OnConnectionReceived != null) { this.OnConnectionReceived(args.Socket); } }
private void TcpServer_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { if (isRunning) { ClientAdded(this, new CustomEventArgs(args.Socket)); } }
private async void OnConnectionReceived( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { try { DisplayOutput(TcpServerOutput, args.Socket.Information.RemoteAddress.DisplayName + " connected."); while (true) { // Read request. string request = await ReadUntilCrLf(args.Socket.InputStream, TcpServerOutput); if (String.IsNullOrEmpty(request)) { // If there was no request. The remote host closed the connection. return; } DisplayOutput(TcpServerOutput, request); // Send response. string response = "Yes, I am ñoño. The time is " + DateTime.Now + ".\r\n"; // In this sample since the server doesn´t close the close the socket, we // could do it async (i.e. without await)., but not now. await Send(args.Socket.OutputStream, response); } } catch (Exception ex) { DisplayOutput(TcpServerOutput, ex.ToString()); } }
private async void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { playPage.DisplayMessages(name + " :Recived TCP: start"); try { playPage.DisplayMessages(name + " " + args.Socket.Information.RemoteAddress.DisplayName + " connected."); while (true) { string request = await Read(args.Socket.InputStream); if (String.IsNullOrEmpty(request)) { return; } playPage.DisplayMessages(name + " :Recived TCP: " + request); OnReceived(request, args.Socket.Information.RemoteAddress.DisplayName, args.Socket.Information.RemotePort); //string response = "Respone.\r\n"; //await Send(args.Socket.OutputStream, response); } } catch (Exception ex) { playPage.DisplayMessages(name + " :Recived TCP\n" + ex.ToString()); } }
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { socket = args.Socket; var dr = new DataReader(socket.InputStream); /// GET ヘッダを取り出し StringBuilder request = new StringBuilder(); uint BufferSize = 1024; using (IInputStream input = socket.InputStream) { byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } // GET method を取り出し string requestMethod = request.ToString().Split('\n')[0]; string[] requestParts = requestMethod.Split(' '); var text = requestParts[1]; /// GETコマンドの受信イベント if (this.OnReceived != null) { OnReceived(text); } }
private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { DataReader reader = new DataReader(args.Socket.InputStream); try { while (true) { // Read first 4 bytes (length of the subsequent string). uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); if (sizeFieldCount != sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data. return; } // Read the string. uint stringLength = reader.ReadUInt32(); uint actualStringLength = await reader.LoadAsync(stringLength); if (stringLength != actualStringLength) { // The underlying socket was closed before we were able to read the whole data. return; } // Display the string. string text = reader.ReadString(actualStringLength); string InLang = "en"; string outLang = "es-MX"; Translator Trans = new Translator(text, InLang, outLang); string translatedS = Trans.GetTranslatedString(); SpeechSynthesisStream stream = await synthesizer.SynthesizeTextToStreamAsync(translatedS); var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { media.SetSource(stream, stream.ContentType); media.Play(); originalmsg.Text = text; ReceivedText.Text = translatedS; ReceivedText.FontSize = 20; }); } } catch (Exception exception) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { StatusText.Text = "Error in Socket reading data from Remote host: " + exception.Message; connected = false; CoreApplication.Properties.Remove("clientSocket"); CoreApplication.Properties.Remove("clientDataWriter"); }); } }
private async void TcpServer_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { if (isRunning) { await ThreadPool.RunAsync(new WorkItemHandler((IAsyncResult) => AddClient(args))); } }
private static async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { ConnectionStatus = ConnectionStatus.Connected; DataReader reader = new DataReader(args.Socket.InputStream); try { while (true) { uint sizeFieldCount = await reader.LoadAsync(sizeof (uint)); if (sizeFieldCount != sizeof (uint)) { return; } uint stringLength = reader.ReadUInt32(); uint actualStringLength = await reader.LoadAsync(stringLength); if (stringLength != actualStringLength) { return; } Message = reader.ReadString(actualStringLength); } } catch (Exception e) { ConnectionStatus = ConnectionStatus.Failed; //TODO:send a connection status message with error } }
/// <summary> /// Called when [connection]. /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The <see cref="StreamSocketListenerConnectionReceivedEventArgs" /> instance containing the event data.</param> private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { StringBuilder request = new StringBuilder(); try { // Get the whole request. using (IInputStream inputStream = args.Socket.InputStream) { Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(BufferLength); do { await inputStream.ReadAsync(buffer, BufferLength, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(buffer.ToArray(), 0, (int)buffer.Length)); } while (buffer.Length == BufferLength); } // Write the response. using (IOutputStream output = args.Socket.OutputStream) { await output.WriteAsync(this.CreateResponse()); } } catch (Exception exception) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } } }
private void listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { this.Log("new Connection received"); _output = args.Socket.OutputStream; try { using (var reader = new StreamReader(args.Socket.InputStream.AsStreamForRead())) { while (!reader.EndOfStream) { var nextLine = reader.ReadLine(); this.Log(nextLine); _input.OnNext(nextLine); } } _input.OnCompleted(); } catch (Exception ex) { this.Log("exception, invalidating socket stuff"); InvalidateSocketStuff(); _input.OnError(ex); } }
private void ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { HasConnection = true; var socket = new ComplexStreamSocket(args.Socket); StartStreaming(socket); HasConnection = false; }
private void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { // Statustext aktualisieren UpdateStatus(string.Format("Verbunden mit {0}...", args.Socket.Information.RemoteHostName)); // Bild übertragen TransferPicture(args.Socket); }
/// <summary> /// Initializes a new instance of the <see cref="ClientConnectedEventArgs" /> class. /// </summary> /// <param name="arg">The channel args.</param> public ClientConnectedEventArgs(StreamSocketListenerConnectionReceivedEventArgs args) { if (args == null) throw new ArgumentNullException("args"); AllowConnect = true; Socket = args.Socket; }
void _listeningSocket_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { _socket = args.Socket; _stream = _socket.OutputStream; if (_acceptAction != null) _acceptAction(this); }
async void listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { readBuffer = new byte[BufferSize]; socket = args.Socket; // Start a background task to continuously read for incoming data Task receiving = Task.Factory.StartNew(ReceiveData, args.Socket, TaskCreationOptions.LongRunning); //WaitForData(socket); }
void listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { while (true) { RealmClass realmClient = new RealmClass(); realmClient.clientSocket = args.Socket; realmClient.streamArgs = args; realmClient.Recieve(null); } }
private void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { Logger.Log("Received Connection - " + args.Socket.Information.RemoteHostName); ((ShellOutput)this.PreferredOutput).SetSocket(args.Socket); dr = new DataReader(args.Socket.InputStream); dr.InputStreamOptions = InputStreamOptions.Partial; julie.brain.ReceivedInput(this, "Hello"); WaitForData(args.Socket); }
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { Debug.WriteLine("Connection Received on Port {0}", sender.Information.LocalPort); StreamSocket streamSocket = args.Socket; if (streamSocket != null) { DataReader reader = new DataReader(streamSocket.InputStream); try { // Read first 4 bytes (length of the subsequent string). uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); if (sizeFieldCount != sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data. return; } // Read the length of the 'packet'. uint length = reader.ReadUInt32(); uint actualLength = await reader.LoadAsync(length); if (length != actualLength) { // The underlying socket was closed before we were able to read the whole data. return; } string name = reader.ReadString(actualLength); Speaker speaker = new Speaker() { Name = name, Address = streamSocket.Information.RemoteAddress.DisplayName, Status = "Connected", Socket = streamSocket }; await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Speakers.Add(speaker); }); reader.DetachStream(); Debug.WriteLine("New speaker added " + name); } catch (Exception e) { Debug.WriteLine("Error in connection received: " + e); } } }
private void OnConnected( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { if (connectedSocket != null) { connectedSocket.Dispose(); connectedSocket = null; } connectedSocket = args.Socket; SendMessageTextBox.IsEnabled = true; SendButton.IsEnabled = true; }
static async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { try { if (IsRobot) { DataReader reader = new DataReader(args.Socket.InputStream); String str = ""; while (true) { uint len = await reader.LoadAsync(1); if (len > 0) { byte b = reader.ReadByte(); str += Convert.ToChar(b); if (b == '.') { Debug.WriteLine("Network Received: '{0}'", str); //Controllers.ParseCtrlMessage(str); break; } } } } else { String lastStringSent; while (true) { DataWriter writer = new DataWriter(args.Socket.OutputStream); lastStringSent = ctrlStringToSend; writer.WriteString(lastStringSent); await writer.StoreAsync(); msLastSendTime = Stopwatch.ElapsedMilliseconds; // re-send periodically long msStart = Stopwatch.ElapsedMilliseconds; for (; ;) { long msCurrent = Stopwatch.ElapsedMilliseconds; if ((msCurrent - msStart) > 3000) break; if (lastStringSent.CompareTo(ctrlStringToSend) != 0) break; } } } } catch (Exception e) { Debug.WriteLine("OnConnection() - " + e.Message); } }
private void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { if (m_pConnectedSocket != null) { m_pConnectedSocket.Dispose(); m_pConnectedSocket = null; } m_pConnectedSocket = args.Socket; m_pCollectingTask = ThreadPool.RunAsync(CollectTelemetryData); var handler = OnClientConnected; handler?.Invoke(this, null); }
private void ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { HasConnection = true; try { var message = _actions.Response(new DataReader(args.Socket.InputStream).GetMessage()); new DataWriter(args.Socket.OutputStream).WriteMessage(message); } catch (Exception exception) { Debug.WriteLine(SocketError.GetStatus(exception.HResult)); } HasConnection = false; }
private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { try { DataReader reader = new DataReader(args.Socket.InputStream); String str = ""; while (true) { uint len = await reader.LoadAsync(1); if (len > 0) { byte b = reader.ReadByte(); str += Convert.ToChar(b); if (b == '.') { //Debug.WriteLine("Network Received: '{0}'", str); //Controllers.ParseCtrlMessage(str); await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { txbReceived.Text = str; }); DataWriter writer = new DataWriter(socket.OutputStream); writer.WriteString(String.Format("Received the following: {0}", str)); await writer.StoreAsync(); str = string.Empty; break; } } } } catch (Exception e) { Debug.WriteLine("OnConnection() - " + e.Message); } }
private async void OnConnected( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { if (connectedSocket != null) { connectedSocket.Dispose(); connectedSocket = null; } connectedSocket = args.Socket; await SendMessageTextBox.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser("Client has connected, go ahead and send a message...", NotifyType.StatusMessage); SendMessageTextBox.IsEnabled = true; SendButton.IsEnabled = true; }); }
private void ListenerOnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { try { if (args.Socket == null) return; var peerSocket = args.Socket; var uri = new Uri("tcp://" + peerSocket.Information.RemoteHostName.RawName + ':' + peerSocket.Information.RemoteServiceName); var peer = new Peer("", uri, EncryptionTypes.All); IConnection connection = new TCPConnection(peerSocket, true); RaiseConnectionReceived(peer, connection, null); } catch { } }
private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { string id = string.Empty; DataReader reader = new DataReader(args.Socket.InputStream); try { while (true) { // Read first 4 bytes (length of the subsequent string). uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); if (sizeFieldCount != sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data. return; } // Read the string. uint stringLength = reader.ReadUInt32(); uint actualStringLength = await reader.LoadAsync(stringLength); if (stringLength != actualStringLength) { // The underlying socket was closed before we were able to read the whole data. return; } // Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal the text back to the UI thread. string readedString = reader.ReadString(actualStringLength); string action = readedString.Split(';')[0].Split(':')[1].ToString(); id = readedString.Split(';')[1].Split(':')[1].ToString(); OnReceivedMessage(new ActionEventArgs(action, id)); } } catch (Exception exception) { OnReceivedMessage(new ActionEventArgs("closed", id)); } }
async void streamSocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { int i = 0; DataReader dataReader = new DataReader(args.Socket.InputStream); DataWriter serverWriter = new DataWriter(args.Socket.OutputStream); try { while (true) { uint sizeCount = await dataReader.LoadAsync(4); uint length = dataReader.ReadUInt32(); uint contentLength = await dataReader.LoadAsync(length); string msg = dataReader.ReadString(contentLength); i++; Deployment.Current.Dispatcher.BeginInvoke(() => msgList.Children.Add( new TextBlock { Text = "服务器接收到的消息:" + msg })); string serverStr = msg + "|" + i; serverWriter.WriteUInt32(serverWriter.MeasureString(serverStr)); serverWriter.WriteString(serverStr); try { await serverWriter.StoreAsync(); } catch (Exception err) { if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse) { } } } } catch (Exception err) { if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse) { } } }
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { var remoteAddress = args.Socket.Information.RemoteAddress.ToString(); if(globalDataSet.DebugMode) Debug.Write("Client is connected. \n"); // Set flag to begin the sending of sensor data (in MainPage) when client is connected globalDataSet.clientIsConnected = true; Stream outStream = args.Socket.OutputStream.AsStreamForWrite(); StreamWriter writer = new StreamWriter(outStream); while (true) { try { bool[] bufferState = globalDataSet.getBufferState(); string[] sendbuffer = globalDataSet.getSendBuffer(); if (bufferState[i]) { writer.Write(sendbuffer[i]); writer.Flush(); } sendbuffer[i] = ""; bufferState[i] = false; globalDataSet.setBufferState(bufferState); globalDataSet.setSendBuffer(sendbuffer); if (i < sendbuffer.Length - 1) i++; else i = 0; } catch (Exception ex) { if(globalDataSet.DebugMode) Debug.Write("Exception in sending \n"); globalDataSet.clientIsConnected = false; return; } } }