public Task WaitForConnectionAsync(CancellationToken cancellationToken) { CheckConnectOperationsServer(); if (State == PipeState.Connected) { throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected); } return(cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : WaitForConnectionAsyncCore()); async Task WaitForConnectionAsyncCore() { Socket acceptedSocket; CancellationTokenSource linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_internalTokenSource.Token, cancellationToken); try { acceptedSocket = await _instance !.ListeningSocket.AcceptAsync(linkedTokenSource.Token).ConfigureAwait(false); } catch (OperationCanceledException) when(!cancellationToken.IsCancellationRequested) { throw new IOException(SR.IO_PipeBroken); } finally { linkedTokenSource.Dispose(); } HandleAcceptedSocket(acceptedSocket); } }
static void Send(string msg) { byte[] data = Encoding.Unicode.GetBytes(msg); var endPoint = CurPerson.RemoteIp as EndPoint; ListeningSocket?.SendTo(data, endPoint); }
private void WaitForConnections() { while (ServerStatus) { Client client = new Client(); try { client.Socket = ListeningSocket.Accept(); // Receive username from client byte[] buff = new byte[512]; int res = client.Socket.Receive(buff); string response = string.Empty; string strMessage = Encoding.Unicode.GetString(buff); client.Username = strMessage.Trim('\0'); client.thread = new Thread(() => ProcessMessaging(client)); Console.WriteLine($"{client.Username} has joined the chat."); ClientList.Add(client); client.thread.Start(); } catch (Exception) { Console.WriteLine("Unable to accept connections."); } } }
/// <summary> /// Stops listening for incoming connections. /// </summary> public void StopListening() { if (ListeningSocket != null) { ListeningSocket.Close(); ListeningSocket = null; } }
private static void Close() { if (ListeningSocket != null) { ListeningSocket.Shutdown(SocketShutdown.Both); ListeningSocket.Close(); ListeningSocket = null; } }
public void WaitForConnection() { CheckConnectOperationsServer(); if (State == PipeState.Connected) { throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected); } // Use and block on AcceptAsync() rather than using Accept() in order to provide // behavior more akin to Windows if the Stream is closed while a connection is pending. Socket accepted = _instance !.ListeningSocket.AcceptAsync().GetAwaiter().GetResult(); HandleAcceptedSocket(accepted); }
public Task WaitForConnectionAsync(CancellationToken cancellationToken) { CheckConnectOperationsServer(); if (State == PipeState.Connected) { throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected); } return(cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : WaitForConnectionAsyncCore()); async Task WaitForConnectionAsyncCore() => HandleAcceptedSocket(await _instance !.ListeningSocket.AcceptAsync().ConfigureAwait(false)); }
public void Close() { if (ListeningSocket != null) { try { ListeningSocket.Close(); } catch (Exception) { } finally { ListeningSocket = null; } } }
private void Stop() { if (!ServerStatus) { return; } Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Stopping server..."); ServerStatus = false; while (ClientList.Count != 0) { Client client = ClientList[0]; ClientList.Remove(client); client.Dispose(); } ListeningSocket.Close(); ListeningSocket = null; Console.WriteLine("Server stopped."); Console.ForegroundColor = ConsoleColor.Gray; }
static void Listening() { try { string msg = CurPerson.Id + " joined!\n"; Send(msg); while (true) { StringBuilder builder = new StringBuilder(); int bytes = 0; byte[] data = new byte[256]; EndPoint remoteIp = new IPEndPoint(IPAddress.Any, CurPerson.RemoteIp.Port); do { bytes = ListeningSocket.ReceiveFrom(data, ref remoteIp); builder.Append(Encoding.Unicode.GetString(data, 0, bytes)); } while (ListeningSocket.Available > 0); if (State == State.pending) { State = State.active; RecreateHistory(); } IPEndPoint fullEndPoint = remoteIp as IPEndPoint; if (fullEndPoint?.Port == CurPerson.RemoteIp.Port && builder.ToString() != String.Empty) { SessionMessages.Add(builder.ToString()); Console.WriteLine(builder.ToString()); } } } catch (Exception) { State = State.pending; //Console.WriteLine("Client is off line, trying to connect..."); } }
/// <summary> /// Processes all data available on the current FastCGI connection and handles the received data. /// </summary> /// <remarks> /// Call this repeatedly to process incoming requests. /// Alternatively, you can call <see cref="Run(int)"/> once, which will call <see cref="Listen(int)"/> and execute this method in an infinite loop. /// Internally, this method manages reconnections on the network socket and calls <see cref="ProcessSingleRecord(Stream, Stream)"/>. /// Returns true if a record was read, false otherwise. /// </remarks> public bool Process() { // When listening, but not currently connected, and not yet waiting for an incoming connection, start the connection accept if (ListeningSocket != null && AcceptAsyncResult == null) { AcceptAsyncResult = ListeningSocket.BeginAccept((r) => { AcceptIsReady = true; }, null); } if (AcceptAsyncResult != null && AcceptAsyncResult.IsCompleted) { var connection = ListeningSocket.EndAccept(AcceptAsyncResult); AcceptIsReady = false; AcceptAsyncResult = ListeningSocket.BeginAccept((r) => { AcceptIsReady = true; }, null); var stream = new FCGIStream(connection); OpenConnections.Add(stream); ApplyTimeoutSetting(); } bool readARecord = false; var currentConnections = OpenConnections.ToArray(); foreach (var stream in currentConnections) { if (!stream.IsConnected) { OpenConnections.Remove(stream); } else { readARecord |= ProcessStream(stream, stream); } } return(readARecord); }
static void Main(string[] args) { int Port = ListeningPort; // Verify arguments if (args.Length < 1 || (args[0] != "IPv4" && args[0] != "IPv6")) { Console.WriteLine("Usage: TCPServer.exe <IPv4 | IPv6> [port]"); return; } if (args.Length >= 2) { Port = System.Convert.ToInt32(args[1].ToString()); } try { Socket ListeningSocket; if (args[0] == "IPv4") { // Create a new socket to listening for client connections. ListeningSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); // Setup a SOCKADDR_IN structure that will tell bind that we // want to listen for connections on all interfaces using port // 5150. IPEndPoint LocalEndPoint = new IPEndPoint(IPAddress.Any, Port); ListeningSocket.Bind(LocalEndPoint); } else // IPv6 { // Create a new socket to listening for client connections. ListeningSocket = new Socket( AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.IP); IPv6EndPoint LocalEndPoint = new IPv6EndPoint(IPv6Address.Any, Port); ListeningSocket.Bind(LocalEndPoint); } ListeningSocket.Listen(5); Console.WriteLine("Server started - Press RETURN to stop the server."); Console.WriteLine("Awaiting socket connections..."); AcceptInfo AI = new AcceptInfo(ListeningSocket); for (int i = 0; i < MaxAsyncAccepts; i++) { AI.ListeningSocket.BeginAccept(AI.AcceptCallback, AI); } Console.ReadLine(); ListeningSocket.Close(); AI.RemoveAllSockets(); Console.WriteLine("Pending connections were closed - press RETURN to stop application"); Console.ReadLine(); } catch (SocketException err) { Console.WriteLine("Error: " + err.Message); } }