- Build a Xamarin App in C# with Xamarin Forms that uses Peer-to-Peer Sync
- Apprenez comment synchroniser les données entre vos appareils sans Sync Gateway ou Couchbase Server
- Configurer les listeners websockets avec différents modes de TLS et d’authentification client
Résumé
Ce tutoriel utilise une application simple de gestion des inventaires pour illustrer la fonctionnalité de synchronisation de bases de données peer-to-peer introduite dans Couchbase Lite 2.8.
Introduction
La version 2.8 de Couchbase Lite prend en charge directement la sécurité. Synchronisation par paire, 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)
Ce tutoriel vous montrera comment :
-
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.
-
Synchroniser les données entre les partenaires connectés
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.
Vous pouvez learn more about Couchbase Lite on our docs site.
Préalables
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)
-
Si vous n'êtes pas familier avec les bases de Couchbase Lite, nous vous recommandons de suivre les instructions ci-dessous. Getting> Started guides
-
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
Vue d'ensemble de l'application
C’est une application d’inventaire simple qui peut être utilisée comme passive> ou active> peer.
L’application utilise une base de données locale qui est déjà remplie de données. Il n’est pas installé de Sync Gateway ou de 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 - Consultez l’état des clients connectés
- Synchroniser directement les données avec les clients connectés
When used as an active peer, users can:
- Log in and enter the
ListenersBrowserPageto start browsing for peers - Se connecter à un auditeur
- Synchroniser directement les données avec les clients connectés
Example 1. The app in action

Installation d'une application
- Clone le repo
git clone <https://github.com/couchbaselabs/couchbase-lite-peer-to-peer-sync-examples>
Essayez-le
- Open the Xamarin .Net project using Visual Studio
- Build and run the project If you are running Android apps on emulators, please see Connecting to Android emulator over localhost
- Vérifiez que vous voyez l’écran d’identification
- If you are having trouble running the Xamarin iOS sample app, please see Having issue running the Xamarin iOS app?

Découvrir le projet d’application
- The Xamarin .Net project comes pre-bundled with some resource files that we will examine here

userdb.cblite2.zip: A zip file containing a prebuilt Couchbase Lite database. It includes the data for a single document. See Modèle de donnéesuserallowlist.jsonListe des utilisateurs clients valides (et mots de passe) dans le système. Cette liste est consultée lorsque le serveur tente d’authentifier les identifiants associés à la demande de connexion en provenance de l’utilisateur.listener-cert-pkey.p12C’est ça PKCS12> Un fichier archive qui inclut un certificat de clé publique correspondant au listener et la clé privée associée. Le certificat est un exemple de certificat généré à l'aide de OpenSSL> outils.listener-pinned-cert.cerC’est le certificat de l’émetteur de clés publiques (le même certificat qui est incorporé dans le fichierlistener-cert-pkey.p12file) in DER encoded format. This cert is pinned on the client replicator and is used for validating server cert during connection setup.
Modèle de données
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 Date et Blob.
Bien qu'il ne soit pas obligatoire ni appliqué de manière systématique, il est recommandé d'inclure une “ type ” property that can serve as a namespace for related documents.
Le document “ Liste ”
L'application traite un seul document avec un “ type ” propriété de “ liste ”.
Un exemple de document serait
{
"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"
}
]
}
Initialisation de la base de données locale
The app extracts a prebuilt database zip file named userdb.cblite2.zip into DBPath cette opération se produit la première fois que la base de données est créée. Elle se déroule indépendamment du fait que l'application soit lancée en mode passif ou actif.
- Ouvrez CoreApp.cs Fichier et localisez
LoadAndInitDBmethod. This method extract and place the Couchbase Lite database inDBPathfor 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 });
- Ouvrez SeasonalItemsViewModel.cs Fichier et localisez
SeasonalItemsViewModelconstructor. 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 propertiesName,QuantityetImagein .Net ObjectSeasonalItem. 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 passif ou serveur
First, we will walk through the steps of using the app in passive peer mode
Initializing Websocket Listener
- Ouvrez ListenerViewModel.cs Fichier et localisez
CreateListenerfunction. 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)
- Initialisez le
URLEndpointListenerConfigurationfor 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. - C’est ici que nous configurons le mode TLS. Dans l’application, nous avons une flag nommée
ListenerTLSModeCela permet à l’application de passer d’un mode à l’autre. Vous pouvez changer de mode en modifiant la valeur de la variable. Voir Test des différents modes TLS - Activez la synchronisation delta. Elle est désactivée par défaut
- Configurer la fonction callback d’authentification du vérificateur de mot de passe qui authentifie l’utilisateur/mot de passe reçu du client lors de la configuration de la réplication. La liste des utilisateurs valides est configurée dans
userallowlist.jsonfichier fourni avec l'application
Test des différents modes TLS
L'application peut être configurée pour tester différents modes TLS comme indiqué ci-dessous en définissant les paramètres suivants : ListenerTLSMode Une propriété dans le CoreApp.cs fichier
public static LISTENER_CERT_VALIDATION_MODE ListenerCertValidationMode = LISTENER_CERT_VALIDATION_MODE.SKIP_VALIDATION
| ListenerTLSMode Value | Comportement |
|---|---|
| SKIP_VALIDATION | Il n'existe pas de TLS. Toute la communication est en clair (mode non sécurisé et non recommandé en production) |
| WITH_ANONYMOUS_AUTH | L’application utilise un certificat signé par elle-même qui est généré automatiquement par Couchbase Lite en tant que TLSIdentity du serveur. Bien que l’authentification du serveur soit omise, toute communication reste néanmoins sécurisée. |
| Chiffré. C’est la configuration par défaut de Couchbase Lite. | |
| WITH_BUNDLED_CERT | L'application génère TLSIdentity du serveur à partir de la clé publique certifiée et de la clé privée intégrées dans le listener-cert-pkey.p12 archive. La communication est cryptée |
| WITH_GENERATED_SELF_SIGNED_CERT | L'application utilise Couchbase Lite CreateIdentity API de commodité pour générer le TLSIdentity du serveur. La communication est cryptée |
Start Websocket Listener
- Ouvrez ListenerViewModel.cs Fichier et localisez
ExecuteStartListenerCommandMéthode.
_urlEndpointListener.Start()
Service d'écoute publicitaire
In the app, we broadcast listener’s IP endpoint over UDP type socket.
- Ouvrez ListenerViewModel.cs Fichier et recherche
Broadcastmethod. 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
- Ouvrez ListenerViewModel.cs Fichier et localisez
ExecuteStartListenerCommandmethod. You can stop the listener after the listener is started.
_urlEndpointListener.Stop()
_urlEndpointListener.Dispose();
Essayez-le
- 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.jsonfile, such as “bob” and “password” - You can find 4 selections (
What's in Season?,Listener,BrowseretLogout) under the “hamburger” menu located on the upper left hand side. - From the
ListenerPage, selectListenerfrom the “hamburger” menu, start the listener by clicking on “Start Listener” button - You can see 2 toolbar items (
BroadcastetPeers) Remarque : 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 - From the
ListenerPage, stop the listener by clicking on “Stop Listener” button
Example 2.App in action – start passive peer

Peer actif ou client
We will walk through the steps of using the app in active peer mode
Découvrir les auditeurs
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.
- Ouvrez ListenersBrowserViewModel.cs Fichier et recherche
ListenersBrowserViewModelconstructor. Here, we create aUdpListenerwith 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);
}
Explorez le contenu dans UdpListener.cs. It includes implementation of creating Socket with Udp ProtocolType, start and stop the listener, and UdpPacketReceived EventHandler.
Initialisation et démarrage de la réplication
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.
- Ouvrez ReplicatorItem.cs Fichier et localisez
ExecuteStartReplicatorCommandméthode. Si vous utilisez Couchbase Lite pour synchroniser les données avec Sync Gateway, ce code devrait vous sembler très familier. Dans cette fonction, nous initialisons une réplication bidirectionnelle vers l’équivalent du peer listener en mode continu. Nous enregistrons également un réplicateur de réplication pour être informé de l’état de la réplication.
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>
- Initialiser une configuration Repicator pour la base de données locale spécifiée et l’endpoint de l’interlocuteur distant
- C’est ici que nous configurons le mode de validation des certificats du serveur TLS – que nous activons ou non la validation des certificats. Cela ne s’appliquerait que si vous aviez activé le support TLS sur l’émetteur, comme discuté dans 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
ListenerCertValidationModeCela vous permet d’essayer les différents modes. Vous pouvez changer le mode en modifiant la valeur de la variable. Voir Test des différents modes d’authentification des serveurs - L'application utilise l'authentification client de base pour s'authentifier auprès du serveur.
- Initialiser le réplicateur
- Commencez la réplication. L’application utilise les événements du réplicateur Listener pour écouter et surveiller la réplication.
Test des différents modes d’authentification des serveurs
Dans 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 Une propriété dans le CoreApp.cs fichier.
Naturally, if you have initialized the listener with TLSDisabled mode, puis ignorez cette section car il n'y a pas de TLS.
public static LISTENER_CERT_VALIDATION_MODE ListenerCertValidationMode = LISTENER_CERT_VALIDATION_MODE.SKIP_VALIDATION
| ListenerCertValidationMode Value | Comportement |
|---|---|
| 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. |
Arrêter la réplication
- Ouvrez ReplicatorItem.cs Fichier et localisez
StopReplicatormethod. 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 withExecuteStartReplicatorCommandMéthode
_repl?.Stop()
Essayez-le
- Follow instructions in the Essayez-le section of [Passive Peer or Server](#passive-peer-or-server to start app in passive mode on a simulator instance or real device.
- Exécutez l’application sur une instance de simulateur distincte ou sur un appareil réel. Si c’est le dernier cas, assurez-vous de signer votre application avec le certificat de développeur approprié.
- Sur l'écran de connexion, connectez-vous en tant qu'un des utilisateurs configurés dans le
userallowlist.jsonfichier tels que “ bob ” et “ mot de passe ”. Pour une pratique, essayez avec un utilisateur non valide et vérifiez que cela échoue. - You can find 4 selections (
What's in Season?,Listener,BrowseretLogout) 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.
NOTE : If the listener is not started before listeners browser (“Browser”) is selected, you will need to click
Broadcasttoolbar item locates on top of theListenerPage(SeeBroadcastin Peer passif ou serveur) NOTE : You will need to manually enter the listener’s IP endpoint (ex. 192.168.0.14:59840) for Xamarin android app. - Cliquez sur la ligne correspondant à l’émetteur. Cela lancera la réplication avec cet émetteur et il devrait passer à l’état « Connu ». NOTE : 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(SeeBroadcastin Peer passif ou serveur) - 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

Synchronisation des données
Une fois la connexion établie entre les peers, vous pouvez commencer le processus de synchronisation. Couchbase Lite s’en charge.
Essayez-le
- Exécutez l’application sur deux ou plusieurs simulateurs ou sur des appareils réels. Si c’est le cas, assurez-vous de signer votre application avec le certificat de développeur approprié.
- Commencez l’écoute sur l’une des instances de l’application. Vous pouvez également avoir plusieurs listeners.
- Connectez les autres instances de l’application au listener
- You can find 4 selections (
What's in Season?,Listener,BrowseretLogout) under “hamburger” menu locates on the upper left hand side. - Enter
SeasonalItemsPageby 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
- Assurez-vous que le processus de synchronisation s’effectue automatiquement avec les autres clients connectés.
Example 4. App in action — sync

Quoi de neuf
Pour une pratique pratique, passez d'un mode TLS à un autre et vérifiez comment l'application se comporte. Vous pouvez également essayer différentes topologies pour connecter les peers.
En savoir plus
Félicitations pour avoir terminé ce tutoriel !
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.
Autres lectures
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?
Go to 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+.