private async Task RemovePeer(MapPeer peer) { this.ClosePeer(peer); if (this._peers.Contains(peer)) { this._peers.Remove(peer); } // await ProximityMapEnvironment.Default.Log("Search for peers...", true); }
private void ClosePeer(MapPeer peer) { if (peer.StreamSocket != null) { peer.StreamSocket.Dispose(); peer.StreamSocket = null; } if (peer.DataWriter != null) { peer.DataWriter.Dispose(); peer.DataWriter = null; } if (peer.DataReader != null) { peer.DataReader.Dispose(); peer.DataReader = null; } }
private async Task PeerReceive(MapPeer peer) { try { // Get body size uint bytesRead = await peer.DataReader.LoadAsync(sizeof(uint)); if (bytesRead == 0) { await this.RemovePeer(peer); return; } uint length = peer.DataReader.ReadUInt32(); // Get message type uint bytesRead1 = await peer.DataReader.LoadAsync(sizeof(uint)); if (bytesRead1 == 0) { await this.RemovePeer(peer); return; } uint type = peer.DataReader.ReadUInt32(); MessageType messageType = (MessageType)Enum.Parse(typeof(MessageType), type.ToString()); // Get body uint bytesRead2 = await peer.DataReader.LoadAsync(length); if (bytesRead2 == 0) { await this.RemovePeer(peer); return; } // Get message string message = peer.DataReader.ReadString(length); // Process message switch (messageType) { case MessageType.PanningExtent: await this.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { Envelope env = (Envelope)Envelope.FromJson(message); this.ProcessExtent(env); } ); break; case MessageType.Ink: await this.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { MapInkLine line = MapInkLine.FromJson(message); this.ProcessInk(line); } ); break; } // Wait for next message await this.PeerReceive(peer); } catch (Exception ex) { Debug.WriteLine("Reading from socket failed: " + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace); //this.RemovePeer(peer); } }
private async Task PeerSend(MapPeer peer, MessageType messagetype, string text) { if (peer.StreamSocket == null) { return; } if (peer.DataWriter == null) { return; } if (string.IsNullOrWhiteSpace(text)) { return; } uint length = peer.DataWriter.MeasureString(text); uint type = (uint)messagetype; peer.DataWriter.WriteUInt32(length); peer.DataWriter.WriteUInt32(type); peer.DataWriter.WriteString(text); uint numBytesWritten = await peer.DataWriter.StoreAsync(); if (numBytesWritten == 0) { // Socket error when sending await this.RemovePeer(peer); } }
private async Task PeerConnect(PeerInformation peer, StreamSocket socket) { // Store socket DataWriter writer = new DataWriter(socket.OutputStream); DataReader reader = new DataReader(socket.InputStream); MapPeer mapPeer = new MapPeer() { PeerInformation = peer, StreamSocket = socket, DataReader = reader, DataWriter = writer }; this._peers.Add(mapPeer); // Listening await ProximityMapEnvironment.Default.Log("Listening...", true); // Commence send/recieve loop await this.PeerReceive(mapPeer); }