// Send a message through a specific dataWriter public async void SendMessageToPeer(String message, ConnectedPeer connectedPeer) { try { if (!connectedPeer._socketClosed) { DataWriter dataWriter = connectedPeer._dataWriter; uint msgLength = dataWriter.MeasureString(message); dataWriter.WriteInt32((int)msgLength); dataWriter.WriteString(message); uint numBytesWritten = await dataWriter.StoreAsync(); if (numBytesWritten > 0) { OnRaiseMessageEvent(new MessageEventArgs("Sent message: " + message + ", number of bytes written: " + numBytesWritten)); } else { OnRaiseSocketErrorEvent(new SocketEventArgs("The remote side closed the socket")); } } } catch (Exception err) { if (!connectedPeer._socketClosed) { OnRaiseSocketErrorEvent(new SocketEventArgs("Failed to send message with error: " + err.Message)); } } }
// Start the send receive operations void PeerFinder_StartSendReceive(StreamSocket socket, PeerInformation peerInformation) { ConnectedPeer connectedPeer = new ConnectedPeer(socket, false, new Windows.Storage.Streams.DataWriter(socket.OutputStream)); _socketHelper.Add(connectedPeer); if (!_peerFinderStarted) { _socketHelper.CloseSocket(); return; } PeerFinder_ConnectionGrid.Visibility = Visibility.Visible; PeerFinder_SendButton.Visibility = Visibility.Visible; PeerFinder_MessageBox.Visibility = Visibility.Visible; PeerFinder_SendToPeerList.Visibility = Visibility.Visible; if (peerInformation != null) { // Add a new peer to the list of peers. ComboBoxItem item = new ComboBoxItem(); item.Content = peerInformation.DisplayName; PeerFinder_SendToPeerList.Items.Add(item); PeerFinder_SendToPeerList.SelectedIndex = 0; } // Hide the controls related to setting up a connection PeerFinder_AcceptButton.Visibility = Visibility.Collapsed; PeerFinder_BrowseGrid.Visibility = Visibility.Collapsed; PeerFinder_AdvertiseGrid.Visibility = Visibility.Collapsed; _socketHelper.StartReader(connectedPeer); }
public async void StartReader(ConnectedPeer connectedPeer) { try { using (var socketReader = new Windows.Storage.Streams.DataReader(connectedPeer._socket.InputStream)) { // Read the message sent by the remote peer uint bytesRead = await socketReader.LoadAsync(sizeof(uint)); if (bytesRead > 0) { uint strLength = (uint)socketReader.ReadUInt32(); bytesRead = await socketReader.LoadAsync(strLength); if (bytesRead > 0) { String message = socketReader.ReadString(strLength); OnRaiseMessageEvent(new MessageEventArgs("Got message: " + message)); StartReader(connectedPeer); // Start another reader } else { OnRaiseSocketErrorEvent(new SocketEventArgs("The remote side closed the socket")); } } else { OnRaiseSocketErrorEvent(new SocketEventArgs("The remote side closed the socket")); } socketReader.DetachStream(); } } catch (Exception e) { if (!connectedPeer._socketClosed) { OnRaiseSocketErrorEvent(new SocketEventArgs("Reading from socket failed: " + e.Message)); } } }
public void Add(ConnectedPeer p) { _connectedPeers.Add(p); }