Quickstart with Peer-to-Peer Sync in C# and Xamarin Forms

  • Build a Xamarin App in C# with Xamarin Forms that uses Peer-to-Peer Sync
  • Scopri come sincronizzare i dati tra dispositivi senza Sync Gateway o Couchbase Server
  • Configurare i listener di websockets con vari modi di autenticazione TLS e client

Abstract

In questo tutorial viene utilizzato un semplice app per il monitoraggio degli inventari per dimostrare la funzionalità di sincronizzazione dei database peer-to-peer introdotta in Couchbase Lite 2.8.

Introduzione

La versione 2.8 di Couchbase Lite supporta la compatibilità nativa con la crittografia sicura Peer-to-Peer Sync, over websocket, between Couchbase Lite enabled clients in IP-based networks without the need for a centralized control point (i.e. you do not need a Sync Gateway or Couchbase Server to get peer-to-peer database sync going)

In questo tutorial verrà spiegato come:

  • Use a UDP type socket to listen on a specified port for peer discovery. Broadcast it’s own IP address over UDP type socket. + NOTE: UWP app needs to be added to the Exception list on the Windows Firewall.

  • Configure a websocket listener to listen to incoming requests. We will walk through various TLS modes and client authentication modes.

  • Start a bi-directional replication from active peer.

  • Sincronizzazione dei dati tra i peer collegati

Throughout this tutorial, these terms are used interchangeably:

  • “passive peer”, “server” and “listener” all refer to the peer on which the websocket listener is startedf
  • “active peer” and “client” both refer to the peer on which the replicator is initialized

We will be using simple inventory apps in Xamarin UWP, iOS, and Android as an example to demonstrate the peer-to-peer functionality.

È possibile learn more about Couchbase Lite on our docs site.

Prerequisiti

This tutorial assumes familiarity with building Xamarin apps with Visual Studio and Couchbase Lite.

  • Visual Studio 2019 (Download it from the Microsoft Website with:

    • Universal Windows Platform component installed
    • Environment setup for Xamarin Development (Xamarin component installed for Android and iOS development)
  • Se non conoscete le basi di Couchbase Lite, si consiglia di seguire le istruzioni riportate nella documentazione. Getting> Started guide

  • Wi-Fi network that the peers can communicate over + You could run your peers in multiple simulators. But if you were running the app on real devices, then you will need to ensure that the devices are on the same WiFi network

Riassunto dell'applicazione

Si tratta di un'app semplice per l'inventario che può essere utilizzata come passive> o active> peer.

L'app utilizza un database locale precompilato con i dati. Non è installato Sync Gateway o Couchbase Server.

When used as a passive peer, users can:

  • Log in and start a websocket listener for the Couchbase Lite database. The Listener IP endpoint is advertised over UDP type socket when users enter the ListenerPage
  • Visualizza lo stato dei client connessi
  • Sincronizza direttamente i dati con i client collegati

When used as an active peer, users can:

  • Log in and enter the ListenersBrowserPage to start browsing for peers
  • Connettersi a un ascoltatore
  • Sincronizza direttamente i dati con i client collegati

Example 1. The app in action

peer to peer sync

Installazione dell'app

  • Clone il repo
git clone <https://github.com/couchbaselabs/couchbase-lite-peer-to-peer-sync-examples>

Provatelo

app login screen

Esplorando il progetto App

  • The Xamarin .Net project comes pre-bundled with some resource files that we will examine here

xcode project explorer

  • userdb.cblite2.zip: A zip file containing a prebuilt Couchbase Lite database. It includes the data for a single document. See Modello dei dati
  • userallowlist.jsonElenco degli utenti client validi (e delle loro password) nel sistema. Questo elenco viene ricercato quando il server tenta di autenticare le credenziali associate alle richieste di connessione in arrivo.
  • listener-cert-pkey.p12Questo è PKCS12> Un archivio di file che include un certificato di chiave pubblica corrispondente al listener e la chiave privata associata. Il certificato è un esempio di certificato generato utilizzando OpenSSL> strumento.
  • listener-pinned-cert.cerQuesto è il certificato per l'ascolto delle chiavi pubbliche (lo stesso certificato che è incorporato nel file listener-cert-pkey.p12 file) in DER encoded format. This cert is pinned on the client replicator and is used for validating server cert during connection setup.

Modello dei dati

Couchbase Lite is a JSON Document Store. A Document is a logical collection of named fields and values. The values are any valid JSON types. In addition to the standard JSON types, Couchbase Lite supports some special types like Data e Blob. Sebbene non sia obbligatorio né applicato in via esplicita, è consigliabile includerlo nella “tipo” property that can serve as a namespace for related documents.

Il documento “List”

L'app gestisce un singolo documento con un “tipo” proprietà di “lista”.

Un esempio di documento sarebbe:

{
  "type": "list",
  "list": [
  {
    "image": {
      "length":16608,
      "digest":"sha1-LEFKeUfywGIjASSBa0l/cg5rlm8=",
      "content_type":"image/jpeg",
      "@type":"blob"
    },
    "value":10,
    "key":"Apples"
  },
  {
    "image": {
      "length":16608,
      "digest":"sha1-LEFKeUsswGIjASssSBa0l/cg5rlm8=",
      "content_type":"image/jpeg",
      "@type":"blob"
    },
    "value":110,
    "key":"oranges"
    }
  ]
}

Inizializzazione del database locale

The app extracts a prebuilt database zip file named userdb.cblite2.zip into DBPath la prima volta in cui viene creata la database. Questo accade indipendentemente dal fatto che l'app sia avviata in modalità passiva o attiva.

  • Apri CoreApp.cs apri il file e trova LoadAndInitDB method. This method extract and place the Couchbase Lite database in DBPath for the user if one does not exist.
if (!Database.Exists(DbName, DBPath))
{
    using (var dbZip = new ZipArchive(ResourceLoader.GetEmbeddedResourceStream(typeof(CoreApp).GetTypeInfo().Assembly, $"{DbName}.cblite2.zip")))
    {
        dbZip.ExtractToDirectory(DBPath);
    }
}
DB = new Database(DbName, new DatabaseConfiguration() { Directory = DBPath });
  • Apri SeasonalItemsViewModel.cs apri il file e trova SeasonalItemsViewModel constructor. It creates a LiveQuery to pick up document changes in the inventory list array when the ViewModel loads the first time. Each array item contains a dictionary with three key value pairs. Their keys are “key”, “value”, and “image” and their values are mapped to the properties Name, Quantity, e Image in .Net Object SeasonalItem. The “image” property holds a blob entry to an image.
 var q = QueryBuilder.Select(SelectResult.All())
    .From(DataSource.Database(_db))
    .Where(Meta.ID.EqualTo(Expression.String(CoreApp.DocId)))
    .AddChangeListener((sender, args) =>
    {
      var allResult = args.Results.AllResults();
      var result = allResult[0];
      var dict = result[CoreApp.DB.Name].Dictionary;
      var arr = dict.GetArray(CoreApp.ArrKey);

      if (arr.Count < Items.Count)
        Items = new ObservableConcurrentDictionary<int, SeasonalItem>();

      Parallel.For(0, arr.Count, i =>
      {
        var item = arr[i].Dictionary;
        var name = item.GetString("key");
        var cnt = item.GetInt("value");
        var image = item.GetBlob("image");

        if (_items.ContainsKey(i)) {
          _items[i].Name = name;
          _items[i].Quantity = cnt;
          _items[i].ImageByteArray = image?.Content;
        } else {
          var seasonalItem = new SeasonalItem {
            Index = i,
            Name = name,
            Quantity = cnt,
            ImageByteArray = image?.Content
          };
          _items.Add(i, seasonalItem);
        }
      });
    });

Peer passivo o server

First, we will walk through the steps of using the app in passive peer mode

Initializing Websocket Listener

  • Apri ListenerViewModel.cs apri il file e trova CreateListener function. This is where the websocket listener for peer-to-peer sync is initialized
var listenerConfig = new URLEndpointListenerConfiguration(_db); // <1>
listenerConfig.NetworkInterface = GetLocalIPv4(NetworkInterfaceType.Wireless80211) ?? GetLocalIPv4(NetworkInterfaceType.Ethernet);
listenerConfig.Port = 0; // Dynamic port

switch (CoreApp.ListenerTLSMode) { // <2>
  case LISTENER_TLS_MODE.DISABLED:
    listenerConfig.DisableTLS = true;
    listenerConfig.TlsIdentity = null;
    //end::TLSDisabled[]
    break;
  case LISTENER_TLS_MODE.WITH_ANONYMOUS_AUTH:
    listenerConfig.DisableTLS = false; // Use with anonymous self signed cert if TlsIdentity is null
    listenerConfig.TlsIdentity = null;
    //end::TLSWithAnonymousAuth[]
    break;
  case LISTENER_TLS_MODE.WITH_BUNDLED_CERT:
    listenerConfig.DisableTLS = false;
    listenerConfig.TlsIdentity = ImportTLSIdentityFromPkc12(ListenerCertLabel);
    break;
  case LISTENER_TLS_MODE.WITH_GENERATED_SELF_SIGNED_CERT:
    listenerConfig.DisableTLS = false;
    listenerConfig.TlsIdentity = CreateIdentityWithCertLabel(ListenerCertLabel);
    break;
}

listenerConfig.EnableDeltaSync = true; // <3>

if (CoreApp.RequiresUserAuth) { // <4>
  listenerConfig.Authenticator = new ListenerPasswordAuthenticator((sender, username, password) =>
  {
    // ** This is only a sample app to use an existing users credential shared cross platforms.
    //    Developers should use SecureString password properly.
    var found = CoreApp.AllowedUsers.Where(u => username == u.Username && new NetworkCredential(string.Empty, password).Password == u.Password).SingleOrDefault();
    return found != null;
  });
}

_urlEndpointListener = new URLEndpointListener(listenerConfig)
  • Initialize il URLEndpointListenerConfiguration for the specified database. There is a listener for a given database. You can specify a port to be associated with the listener. In our app, we let Couchbase Lite choose the port.
  • Qui è possibile configurare il modo di funzionamento di TLS. Nell'app abbiamo una variabile denominata ListenerTLSMode questo consente all'app di passare tra i vari modi. È possibile cambiare il modo modificando il valore della variabile. Vedere Testando diversi modi di TLS
  • Attiva la sincronizzazione delta. Di default è disabilitata
  • Configura la funzione di callback dell'autenticatore della password che autentica l'username/password ricevuto dal client durante la configurazione della replicazione. La lista degli utenti validi è configurata in userallowlist.json file incluso nella app
Testando diversi modi di TLS

L'app può essere configurata per testare diversi modi di TLS come segue impostando la variabile ListenerTLSMode immobiliari nel CoreApp.cs file

public static LISTENER_CERT_VALIDATION_MODE ListenerCertValidationMode = LISTENER_CERT_VALIDATION_MODE.SKIP_VALIDATION
ListenerTLSMode Value Comportamento
SKIP_VALIDATION Non è presente TLS. Tutte le comunicazioni sono in chiaro (modalità non sicura e non consigliata in produzione)
WITH_ANONYMOUS_AUTH L'app utilizza un certificato auto-firmato generato automaticamente da Couchbase Lite come TLSIdentity del server. Sebbene l'autenticazione del server venga ignorata, tutta la comunicazione continua a essere crittografata.
crittografato. Questo è il modo di funzionamento predefinito di Couchbase Lite.
WITH_BUNDLED_CERT L'app genera TLSIdentity del server a partire dalla chiave pubblica del certificato e dalla chiave privata integrata nel listener-cert-pkey.p12 archivio. La comunicazione è criptata
WITH_GENERATED_SELF_SIGNED_CERT L'app utilizza Couchbase Lite CreateIdentity API per la generazione della convenienza TLSIdentity del server. La comunicazione è criptata

Start Websocket Listener

  • Apri ListenerViewModel.cs apri il file e trova ExecuteStartListenerCommand metodo.
_urlEndpointListener.Start()

Servizio di ascolto pubblicitario

In the app, we broadcast listener’s IP endpoint over UDP type socket.

  • Apri ListenerViewModel.cs file e cercare Broadcast method. Here, we create a Socket with Udp ProtocolType and broadcast listener’s IP endpoint to the peers are listening in local network. Please note, this App requires peers to start peer discovery before listener start broadcasting. Otherwise, you will have to manually broadcast the listener IP. Please see <<tryit10,Try it out>> for detail.
public void Broadcast()
{
  if (!IsListening)
    return;

  using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp)) {
    socket.EnableBroadcast = true;
    var group = new IPEndPoint(IPAddress.Broadcast, CoreApp.UdpPort);
    var hi = Encoding.ASCII.GetBytes($"{CoreApp.Guid}:{_urlEndpointListener.Urls[0].Host}:{_urlEndpointListener.Port}");
    socket.SendTo(hi, group);
    socket.Close();
  }
}

Stop Websocket Listener

  • Apri ListenerViewModel.cs apri il file e trova ExecuteStartListenerCommand method. You can stop the listener after the listener is started.
_urlEndpointListener.Stop()
_urlEndpointListener.Dispose();

Provatelo

  • Run the app on a simulator or a real device. If it’s the latter, make sure you sign your app with the appropriate developer certificate
  • On the login screen, sign in as any one of the users configured in the userallowlist.json file, such as “bob” and “password”
  • You can find 4 selections (What's in Season?, Listener, Browser, e Logout) under the “hamburger” menu located on the upper left hand side.
  • Da parte del ListenerPage, select Listener from the “hamburger” menu, start the listener by clicking on “Start Listener” button
  • You can see 2 toolbar items (Broadcast e Peers) Nota: These two items will do nothing if listener is not started.
  • Click on the “Peers” toolbar item to see the number of connected clients. It should be zero if there are no connected clients
  • If you don’t see your listener’s IP endpoint showing up on a peers’ ListenersBrowserPage, click on the listener’s “Broadcast” toolbar item to broadcast its IP endpoint
  • Da parte del ListenerPage, stop the listener by clicking on “Stop Listener” button

Example 2.App in action – start passive peer

server websocket listener login screen

Peer attivo o Cliente

We will walk through the steps of using the app in active peer mode

Scoprire i Suoi Oientatori

In the app, we use UDP Type Socket to listen on port 15000 for listener. Please note, port 15000 is used by UDP Type Socket, not used by the websocket listener. Couchbase Lite choose the port when a websocket listener is created.

  • Apri ListenersBrowserViewModel.cs file e cercare ListenersBrowserViewModel constructor. Here, we create a UdpListener with the port it listens on and pick up any raised Udp packet received event (Listener’s broadcasting IP endpoint).
{
  Title = "Browser";
  Items = new ObservableCollection<ReplicatorItem>();

  _discovery = new UdpListener(CoreApp.UdpPort);
  _discovery.UdpPacketReceived += DiscoveryOnUdpPacketReceived;
  _discovery.Start();
}

# region discover event

private void DiscoveryOnUdpPacketReceived(object sender, UdpPacketReceivedEventArgs args)
{
  var msg = Encoding.ASCII.GetString(args.Data);
  var msgArr = msg.Split(':');
  var remoteId = Guid.Parse(msgArr[0]);
  if (remoteId == CoreApp.Guid) return;
  var remoteIP = IPAddress.Parse(msgArr[1]);
  var remotePort = Int32.Parse(msgArr[2]);
  var remoteEndpoint = new IPEndPoint(remoteIP, remotePort);

  AddReplicator(remoteEndpoint);
}

Esplora il contenuto nel UdpListener.cs. It includes implementation of creating Socket with Udp ProtocolType, start and stop the listener, and UdpPacketReceived EventHandler.

Inizializzazione e avvio della replica

Initializing a replicator for peer-to-peer sync is fundamentally the same as if the Couchbase Lite client were to sync> with a remote Sync Gateway.

  • Apri ReplicatorItem.cs apri il file e trova ExecuteStartReplicatorCommand metodo. Se avete utilizzato Couchbase Lite per sincronizzare i dati con Sync Gateway, questo codice dovrebbe risultare molto familiare. In questa funzione inizializziamo una replica bidirezionale con il peer listener in modalità continua. Inoltre registriamo un Replication Listener per essere informato dello stato della replica.
public ReplicatorItem(IPEndPoint listenerEndpoint)
{
  _listenerEndpoint = listenerEndpoint;
  StartReplicatorCommand = new Command(() => ExecuteStartReplicatorCommand());
  CreateReplicator(ListenerEndpointString);
}

~ReplicatorItem()
{
    Dispose(disposing: false);
}

# endregion

public void CreateReplicator(string PeerEndpointString)
{
  if(_repl != null) {
    return;
  }

  Uri host = new Uri(PeerEndpointString);
  var dbUrl = new Uri(host, _db.Name);
  var replicatorConfig = new ReplicatorConfiguration(_db, new URLEndpoint(dbUrl)); // <1>
  replicatorConfig.ReplicatorType = ReplicatorType.PushAndPull;
  replicatorConfig.Continuous = true;

  if (CoreApp.ListenerTLSMode > 0) {

    // Explicitly allows self signed certificates. By default, only
    // CA signed cert is allowed
    switch (CoreApp.ListenerCertValidationMode) { // <2>
      case LISTENER_CERT_VALIDATION_MODE.SKIP_VALIDATION:
        // Use acceptOnlySelfSignedServerCertificate set to true to only accept self signed certs.
        // There is no cert validation
        replicatorConfig.AcceptOnlySelfSignedServerCertificate = true;
        break;

      case LISTENER_CERT_VALIDATION_MODE.ENABLE_VALIDATION_WITH_CERT_PINNING:
        // Use acceptOnlySelfSignedServerCertificate set to false to only accept CA signed certs
        // Self signed certs will fail validation

        replicatorConfig.AcceptOnlySelfSignedServerCertificate = false;

        // Enable cert pinning to only allow certs that match pinned cert

        try {
            var pinnedCert = LoadSelfSignedCertForListenerFromBundle();
            replicatorConfig.PinnedServerCertificate = pinnedCert;
        } catch (Exception ex) {
            Debug.WriteLine($"Failed to load server cert to pin. Will proceed without pinning. {ex}");
        }

        break;

      case LISTENER_CERT_VALIDATION_MODE.ENABLE_VALIDATION:
        // Use acceptOnlySelfSignedServerCertificate set to false to only accept CA signed certs
        // Self signed certs will fail validation. There is no cert pinning
        replicatorConfig.AcceptOnlySelfSignedServerCertificate = false;
        break;
    }
  }

  if (CoreApp.RequiresUserAuth) {
    var user = CoreApp.CurrentUser;
    replicatorConfig.Authenticator = new BasicAuthenticator(user.Username, user.Password); // <3>
  }

  _repl = new Replicator(replicatorConfig); // <4>
  _listenerToken = _repl.AddChangeListener(ReplicationStatusUpdate);
}

public void ExecuteStartReplicatorCommand()
{
  if (!IsStarted) {
    _repl.Start(); // <5>
  • Initialize una configurazione Repicator per il database locale specificato e l'endpoint dell'URL del listener remoto
  • È qui che configuriamo la modalità di convalida dei certificati del server TLS: se attiviamo la convalida dei certificati o se saltiamo la convalida. Ciò si applicerebbe solo se avessimo attivato il supporto TLS sul listener, come discusso in tlsmodes,TLS Modes on Listener. If you skip server cert validation, you still get encrypted communication, but you are communicating with an un-trusted listener. In the app, we have a flag named ListenerCertValidationMode che consente di provare i vari modi di funzionamento. È possibile cambiare il modo di funzionamento modificando il valore della variabile. Vedere Testando diversi modi di autenticazione dei server
  • L'app utilizza l'autenticazione client base per autenticarsi con il server
  • Inizializzare il Replicator
  • Inizia la replicazione. L'app utilizza gli eventi presenti nel Replicator Listener per monitorare e gestire la replicazione.
Testando diversi modi di autenticazione dei server

In Initializing Websocket Listener section, we discussed the various ways the listener TLSIdentity can be configured. Here, we describe the corresponding changes on the replicator side to authenticate the server identity. The app can be configured to test the different TLS modes (tlscertauth) by setting the ListenerCertValidationMode immobiliari nel CoreApp.cs file.

Naturally, if you have initialized the listener with TLSDisabled se si utilizza la modalità "Modo", allora ignorare questa sezione poiché non è presente TLS.

public static LISTENER_CERT_VALIDATION_MODE ListenerCertValidationMode = LISTENER_CERT_VALIDATION_MODE.SKIP_VALIDATION
ListenerCertValidationMode Value Comportamento
SKIP_VALIDATION There is no authentication of server cert. The server cert is a self-signed cert. This is typically used in dev or test environments. Skipping server cert authentication
is discouraged in production environments. Communication is encrypted.
ENABLE_VALIDATION If the listener cert is from a well known CA then you will use this mode. Of course, in our sample app, the istener cert as specified in listener-cert-pkey is a self
signed cert – so you probably will not use this mode to to test. But if you have a CA signed cert, you can configure your listener with the CA signed cert and use this
mode to test. Communication is encrypted.
ENABLE_VALIDATION_WITH_CERT_PINNING In this mode, the app uses the pinned cert,listener-pinned-cert.cer that is bundled in the app to validate the listener identity. Only the server cert that exactly matches
the pinned cert will be authenticated. Communication is encrypted.

Interruzione della replicazione

  • Apri ReplicatorItem.cs apri il file e trova StopReplicator method. If you have been using Couchbase Lite to sync data with Sync Gateway, this code should seem very familiar. In this function, we remove any listeners attached to the replicator and stop it. You can restart the replicator with ExecuteStartReplicatorCommand metodo
_repl?.Stop()

Provatelo

  • Follow instructions in the Provatelo section of [Passive Peer or Server](#passive-peer-or-server to start app in passive mode on a simulator instance or real device.
  • Esegui l'app su un'istanza separata del simulatore o su un dispositivo reale. Se si tratta di quest'ultimo, assicurati di firmare l'app con il certificato di sviluppatore appropriato.
  • Nella schermata di login, effettuate l'accesso come uno degli utenti configurati nel userallowlist.json file come “bob” e “password”. Come esercitazione, provate con un utente non valido e verificate che non funzioni.
  • You can find 4 selections (What's in Season?, Listener, Browser, e Logout) under the “hamburger” menu located on the upper left hand side.
  • Select “Browser” from the “hamburger” menu. The app automatically browses for listener and lists it here when any listener is broadcasting. NOTA: If the listener is not started before listeners browser (“Browser”) is selected, you will need to click Broadcast toolbar item locates on top of the ListenerPage (See Broadcast in Peer passivo o server) NOTA: You will need to manually enter the listener’s IP endpoint (ex. 192.168.0.14:59840) for Xamarin android app.
  • Tocca la riga corrispondente all'ascoltatore. Ciò inizierà la replicazione con l'ascoltatore e dovrebbe passare allo stato Connesso NOTA: If you Cannot connect Android app active peer to passive peer when you are using Xamarin.Android SDK 9.x or other older version?
  • Verify the connection count on listener by clicking “Peers” toolbar item locates on top of the ListenerPage (See Broadcast in Peer passivo o server)
  • Tap on the row corresponding to listener again. This will stop replication with the listener and it should transition to Disconnected state. Try Disconnect and then reconnect again
  • Swipe left (iOS) or long press (Android) or left click (UWP) on the the row. You should see the option to remove listener

Example 3. App in action — start active peer

p2p sync

Sincronizzazione dei dati

Una volta stabilita la connessione tra i peer, è possibile iniziare la sincronizzazione. Couchbase Lite si occupa di tutto.

Provatelo

  • Esegui l'app su due o più simulatori o dispositivi reali. Se si tratta di quest'ultimo, assicurati di firmare l'app con il certificato del relativo sviluppatore.
  • Iniziare l'ascolto su una delle istanze dell'app. È possibile anche avere più ascoltatori.
  • Connettete le altre istanze dell'app all'ascoltatore
  • You can find 4 selections (What's in Season?, Listener, Browser, e Logout) under “hamburger” menu locates on the upper left hand side.
  • Enter SeasonalItemsPage by selecting “What’s in Season?” from the “hamburger” menu.
  • Edit the quantity and/or image on one or multiple instance(s) and press Save when you are done editing
  • Assicuratevi che la sincronizzazione avvenga automaticamente con gli altri client collegati

Example 4. App in action — sync

server websocket listener login screen

Che succederà dopo?

Per esercitarsi, passare tra i vari modi di TLS e i modi di convalida dei certificati del server e vedere come si comporta l'applicazione. È anche possibile provare con diverse topologie per connettere i peer.

Ulteriori informazioni

Complimenti per aver completato questo tutorial!

This tutorial walked you through an example of how to directly synchronize data between Couchbase Lite enabled clients. While the tutorial is for Xamarin .Net, the concepts apply equally to other Couchbase Lite platforms.

Per ulteriori informazioni

Checkout the complete documentation on our docs site.

Troubleshoot

Having issue running the Xamarin iOS app?

  • Xamarin iOS p2p sample app should build and run with Visual Studio 2019 with latest updates and XCode 12.0.1
  • If you have Xcode 11 and try to run the iOS app on simulator and the simulator is not loading, try launch the simulator via Xcode and select that simulator when launching it from VS.

Connecting to Android emulator over localhost

When starting a listener on Android emulator and trying to connect it from another emulator or iOS simulator on localhost, the following steps must be followed

  • Setup port forwarding. For instance, if the listener is listening on port 35262, the command to run on the terminal of the host machine would be:
adb forward tcp:35262 tcp:35262
  • You cannot connect to emulator directly over localhost.
    Regardless of the IP address in the displayed URL, the replicator app must ignore it and use “127.0.0.1” as the host address.
    For example, if the listener is listening on “10.2.0.15: 35262” , then you must connect to URL “127.0.0.1: 35262”.

Cannot connect Android app active peer to passive peer when you are using Xamarin.Android SDK 9.x or other older version?

Andare su Advanced Android Options (Android Project Properties -> Android Options -> Advanced button) and change SSL/TLS implementation configuration to Managed TLS 1.0 from Native TLS 1.2+.

Lasciare la proliferazione dei database nel passato

Ogni aggiunta di stack significa un altro conto da gestire. Calcola in 2 minuti quanto puoi risparmiare.