public void HandleEnter() { IListenerSocket listener = null; IConnectedSocket client = null; var connectEndpoint = networkingProxy.CreateEndPoint(clusteringConfiguration.Address, clusteringConfiguration.Port); var hostAllowed = !clusteringConfiguration.ClusteringRole.HasFlag(ClusteringRole.GuestOnly) && IPAddress.IsLoopback(clusteringConfiguration.Address); var guestAllowed = !clusteringConfiguration.ClusteringRole.HasFlag(ClusteringRole.HostOnly); while (listener == null && client == null) { if (hostAllowed && TryCreateHostListener(clusteringConfiguration, out listener)) { break; } if (guestAllowed && TryCreateGuestSocket(connectEndpoint, out client)) { break; } logger.Warn("Unable to either listen/connect to port " + clusteringConfiguration.Port); threadingProxy.Sleep(kRetryInterval); } if (listener != null) { clusteringPhaseManager.Transition(clusteringPhaseFactory.CreateHostPhase(localServiceContainer, listener)); } else { clusteringPhaseManager.Transition(clusteringPhaseFactory.CreateGuestPhase(localServiceContainer, client)); } phaseTransitionedLatch.Release(int.MaxValue); }
/// <summary> Function used to disconnect from the server </summary> public void Close() { if (fSocketServer != null) { fSocketServer.RemoveSocket(this); } try { // Notify any listeners that the socket has closed CallMessageHandler(fCloseHandler); } catch {} // Close down the connection if (fStream != null) { fStream.Close(); fStream = null; } if (fWrappedSocket != null) { try { fWrappedSocket.Shutdown(SocketShutdown.Both); } finally { fWrappedSocket.Close(); } } // Clean up the connection state fWrappedSocket = null; fStream = null; }
private bool TryCreateGuestSocket(ITcpEndPoint connectEndpoint, out IConnectedSocket client) { try { client = networkingProxy.CreateConnectedSocket(connectEndpoint); return(true); } catch (SocketException) { client = null; return(false); } }
public static IObservable <Unit> Serve( IConnectedSocket socket, int buffersize, Action <string> log, Func <Request, Func <WSFrame, IObservable <WSFrame> > > route, IScheduler s = null) => Observable.Using( resourceFactory: () => socket, observableFactory: c => c .Receive(buffersize, log) .Select(x => x.ToObservable(s ?? Scheduler.Default)) .Concat() .Publish( bs => Handshake(bs) .SelectMany(x => Accept(x, bs, route))) .SelectMany(x => socket.Write(x)));
public static IObservable <IEnumerable <byte> > Receive( this IConnectedSocket socket, int buffersize, Action <string> log, IScheduler s = null) { return(Observable.Return((socket: socket, buffer: new byte[buffersize])) .SelectMany(x => x.socket .Read(x.buffer, s ?? Scheduler.Default) .Select(r => x.buffer.Take(r).ToArray())) .Repeat() .TakeWhile(x => x.Length > 0) .Catch <byte[], ObjectDisposedException>(ex => Observable.Empty <byte[]>()) .Catch <byte[], IOException>(ex => Observable.Empty <byte[]>()) ); }
internal async Task ProcessSessionAsync(IConnectedSocket socket) { logger.Info("Entering Host Phase SessionThreadEntryPoint"); HostSession session = null; try { session = hostSessionFactory.Create(hostContext, socket); sessions.Add(session); await session.StartAndAwaitShutdown(); } catch (SocketException e) { logger.Warn(e); } catch (Exception e) { logger.Error(e); } finally { sessions.Remove(session); } logger.Info("Exiting Host Phase SessionThreadEntryPoint"); }
public HostSession Create(HostContext hostContext, IConnectedSocket socket) { var shutdownCancellationTokenSource = threadingProxy.CreateCancellationTokenSource(); var pofStream = pofStreamsFactory.CreatePofStream(socket.Stream); var pofDispatcher = pofStreamsFactory.CreateDispatcher(pofStream); var messageSender = new MessageSenderImpl(pofStream.Writer, portableObjectBoxConverter); var session = new HostSessionImpl( hostContext, shutdownCancellationTokenSource, messageSender, pofDispatcher, collectionFactory.CreateConcurrentSet <Guid>(), collectionFactory.CreateUniqueIdentificationSet(true), collectionFactory.CreateConcurrentDictionary <uint, AsyncValueBox>() ); session.Initialize(); return(session); }
/// <summary> /// Constructor for SocketServer Supppor /// </summary> /// <param name="server">A Reference to the parent SocketServer</param> /// <param name="wrappedSocket">RetType: The Socket object we are encapsulating</param> /// <param name="sizeOfRawBuffer">The size of the raw buffer</param> /// <param name="messageHandler">Reference to the user defined message handler function</param> /// <param name="closeHandler">Reference to the user defined close handler function</param> /// <param name="errorHandler">Reference to the user defined error handler function</param> public AdkSocketConnection( AdkSocketBinding server, IConnectedSocket wrappedSocket, int sizeOfRawBuffer, AdkSocketMessageHandler messageHandler, AdkSocketMessageHandler closeHandler, AdkSocketErrorHandler errorHandler ) { // Create the raw buffer fRawBufferSize = sizeOfRawBuffer; fRawBuffer = new Byte[sizeOfRawBuffer]; // Set the handler functions fMessageHandler = messageHandler; fCloseHandler = closeHandler; fErrorHandler = errorHandler; // Set the async socket function handlers fReadCompleteCallback = new AsyncCallback(ReceiveComplete); // Set reference to SocketServer fSocketServer = server; // Init the socket references fWrappedSocket = wrappedSocket; // Init the NetworkStream reference fStream = fWrappedSocket.CreateStream(FileAccess.ReadWrite, false); // Set these socket options fWrappedSocket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, sizeOfRawBuffer); fWrappedSocket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendBuffer, sizeOfRawBuffer); fWrappedSocket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.DontLinger, 1); fWrappedSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); // Wait for a message Receive(); }
/// <summary> /// Constructor for SocketServer Supppor /// </summary> /// <param name="server">A Reference to the parent SocketServer</param> /// <param name="wrappedSocket">RetType: The Socket object we are encapsulating</param> /// <param name="sizeOfRawBuffer">The size of the raw buffer</param> /// <param name="messageHandler">Reference to the user defined message handler function</param> /// <param name="closeHandler">Reference to the user defined close handler function</param> /// <param name="errorHandler">Reference to the user defined error handler function</param> public AdkSocketConnection( AdkSocketBinding server, IConnectedSocket wrappedSocket, int sizeOfRawBuffer, AdkSocketMessageHandler messageHandler, AdkSocketMessageHandler closeHandler, AdkSocketErrorHandler errorHandler ) { // Create the raw buffer fRawBufferSize = sizeOfRawBuffer; fRawBuffer = new Byte[sizeOfRawBuffer]; // Set the handler functions fMessageHandler = messageHandler; fCloseHandler = closeHandler; fErrorHandler = errorHandler; // Set the async socket function handlers fReadCompleteCallback = new AsyncCallback( ReceiveComplete ); // Set reference to SocketServer fSocketServer = server; // Init the socket references fWrappedSocket = wrappedSocket; // Init the NetworkStream reference fStream = fWrappedSocket.CreateStream( FileAccess.ReadWrite, false ); // Set these socket options fWrappedSocket.SetSocketOption ( SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, sizeOfRawBuffer ); fWrappedSocket.SetSocketOption ( SocketOptionLevel.Socket, SocketOptionName.SendBuffer, sizeOfRawBuffer ); fWrappedSocket.SetSocketOption ( SocketOptionLevel.Socket, SocketOptionName.DontLinger, 1 ); fWrappedSocket.SetSocketOption( SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1 ); // Wait for a message Receive(); }
protected virtual void OnMaxConnectionsReached( IConnectedSocket connectedSocket ) { }
/// <summary> Function to process and accept socket connection requests </summary> private void AcceptNewConnection(IAsyncResult ar) { if (fIsShuttingDown) { return; } IConnectedSocket clientSocket = null; try { // Call the derived class's accept handler clientSocket = fAcceptSocket.EndAccept(ar); if (!clientSocket.Connected) { return; } lock (fSocketConnections.SyncRoot) { try { // If we have room to accept this connection if (fSocketConnections.Count <= MaxClientConnections) { // Create a AdkSocketConnection object AdkSocketConnection adkSocket = new AdkSocketConnection ( this, clientSocket, RawBufferSize, DataReceived, SocketClosed, SocketError ); // Call the Accept Handler fSocketConnections.Add(adkSocket); if (SocketAccepted != null) { try { SocketAccepted(adkSocket); } catch { } } } else { OnMaxConnectionsReached(clientSocket); // Close the socket connection clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); } } catch (SocketException e) { // Did we stop the TCPListener if (e.ErrorCode == 10004) { // The connection is being shut down, ignore the error } else { OnError(e); // Close the socket down if it exists if (clientSocket != null && clientSocket.Connected) { clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); } } } catch (Exception ex) { OnError(ex); // Close the socket down if it exists if (clientSocket != null && clientSocket.Connected) { clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); } } } } catch (SocketException e) { // Did we stop the TCPListener if (e.ErrorCode == 10004) { // We're done return; } else { OnError(e); // Close the socket down if it exists if (clientSocket != null && clientSocket.Connected) { clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); } } } finally { if (fIsRunning) { fAcceptSocket.BeginAccept(new AsyncCallback(AcceptNewConnection), null); } } }
protected virtual void OnMaxConnectionsReached(IConnectedSocket connectedSocket) { }
/// <summary> Function used to disconnect from the server </summary> public void Close() { if ( fSocketServer != null ) { fSocketServer.RemoveSocket( this ); } try { // Notify any listeners that the socket has closed CallMessageHandler( fCloseHandler ); } catch {} // Close down the connection if ( fStream != null ) { fStream.Close(); fStream = null; } if ( fWrappedSocket != null ) { try { fWrappedSocket.Shutdown( SocketShutdown.Both ); } finally { fWrappedSocket.Close(); } } // Clean up the connection state fWrappedSocket = null; fStream = null; }
public ClusteringPhase CreateGuestPhase(LocalServiceContainer localServiceContainer, IConnectedSocket clientSocket) { var pofStream = pofStreamsFactory.CreatePofStream(clientSocket.Stream); var pofDispatcher = pofStreamsFactory.CreateDispatcher(pofStream); var messageSender = new MessageSenderImpl(pofStream.Writer, portableObjectBoxConverter); var phase = new GuestPhase( this, localServiceContainer, clusteringPhaseManager, messageSender, pofDispatcher, collectionFactory.CreateUniqueIdentificationSet(true), collectionFactory.CreateConcurrentDictionary <uint, AsyncValueBox>() ); phase.Initialize(); return(phase); }