private int MessageDecoder(byte[] message, int validator) { if (ApplicationId != BitConverter.ToInt32(message, 0)) { if (LogValidationIssues) { Log(NetUtility.Error(ECode.Discovery_Msg_IncorrectAppId)); } return(-1); } else if (ApprovalNumber != BitConverter.ToInt32(message, 4)) { if (LogValidationIssues) { Log(NetUtility.Error(ECode.Discovery_Msg_IncorrectAppNum)); } return(-2); } else if (validator != BitConverter.ToInt32(message, 8)) { if (LogValidationIssues) { Log(NetUtility.Error(ECode.Discovery_Msg_FailedValidation)); } return(-3); } else { return(BitConverter.ToInt32(message, 12)); } }
// AccepterTask's action private void ConnectionAccepter() { while (listener != null && listener.IsBound) { Socket newConnection = null; try { newConnection = listener.Accept(); } catch (Exception) { break; } if (newConnection == null || !newConnection.Connected) { break; } newConnection.NoDelay = UseNoDelay; var netCon = new NetConnection(newConnection, OnConnectionStatusChanged); if (Connections.TryAdd(netCon.RemoteId, netCon)) { OnConnectionAdded(netCon); } else { Log(NetUtility.Error(ECode.Server_FailedConnectionAdd)); netCon.Dispose(); } if (AutoStartReceiver) { netCon.StartReceiverTask(); } } Log("Connection accepter shut down."); OnListenerStatusChanged(false); }
/// <summary> /// Starts/restarts the listener on a Local IP. /// </summary> /// <param name="listenerEndPoint">Listener IP end point. If null it uses LAN IP with any available port.</param> /// <param name="backlog">The maximum length of the pending connections queue.</param> public void StartListener(IPEndPoint listenerEndPoint = null, int backlog = 10) { //Stops the listener if there is any. StopListener(); //Create a socket for the listener server. try { listener = new Socket(PreferredAddressFamily, SocketType.Stream, ProtocolType.Tcp); } catch (SocketException ex) { Log(NetUtility.Error(ECode.Server_LocalIPNotFound)); Log(ex.Message); StopListener(); return; } Log("Listener socket created."); if (listenerEndPoint == null) { //Get local IP address IPAddress localIP = NetUtility.GetLocalIPAddress(PreferredAddressFamily); if (localIP == null) { Log(NetUtility.Error(ECode.Server_FailedToCreateListenerSocket)); StopListener(); return; } listenerEndPoint = new IPEndPoint(localIP, 0); } //Bind the socket to the local IP address. try { listener.Bind(listenerEndPoint); } catch (Exception ex) { Log(NetUtility.Error(ECode.Server_FailedToBindListener)); Log(ex.Message); StopListener(); return; } listenerEndPoint = (IPEndPoint)listener.LocalEndPoint; Log($"Listener socket bound to {listenerEndPoint.Address}:{listenerEndPoint.Port}"); //Start the listening. listener.Listen(backlog); Log("Listener started listening."); //Create a task for accepting connections. Async socket stuff? Log("Waiting for incoming connections..."); OnListenerStatusChanged(true); accepterTask = Task.Factory.StartNew(ConnectionAccepter, TaskCreationOptions.LongRunning); }
// Events handling private void NetServer_ConnectionStatusChanged(object sender, ConnectionStatusChangedEventArgs e) { if (e.Status == NetConnectionStatus.Disconnected) { if (Connections.TryRemove(e.RemoteId, out var connection)) { if (connection != null) { connection.StatusChanged -= OnConnectionStatusChanged; } OnConnectionRemoved(e.RemoteId); } else { Log(NetUtility.Error(ECode.Server_FailedConnectionRemove)); } } }
/// <summary> /// Connect to a specified IP. Disconnects from the current connection on successful connect. /// </summary> /// <param name="ipEndPoint">IP to connect to</param> public void Connect(IPEndPoint ipEndPoint) { if (ipEndPoint == null) { Log("IPEndPoint is null"); return; } lock (connectLock) { Socket clientSocket = null; try { clientSocket = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); } catch (SocketException ex) { Log(NetUtility.Error(ECode.Client_FailedToCreateConnectionSocket)); Log(ex.Message); clientSocket?.Dispose(); return; } clientSocket.NoDelay = UseNoDelay; try { clientSocket.Connect(ipEndPoint); } catch (Exception ex) { Log(NetUtility.Error(ECode.Client_FailedToConnect)); Log(ex.Message); clientSocket?.Dispose(); return; } Connection?.Dispose(); Connection = new NetConnection(clientSocket, OnConnectionStatusChanged); OnConnectionAdded(Connection); if (AutoStartReceiver) { Connection?.StartReceiverTask(); } } }