/// <summary> /// Send the message to the server /// </summary> /// <param name="type">KB or M</param> /// <param name="message">Single character or x,y</param> /// <param name="hold">0=default, 1=press, 2=release</param> public void send(string type, string message, int hold = 0) { try { //NetworkStream clientStream = client.GetStream(); DataWriter writer = new DataWriter(client.OutputStream); //ASCIIEncoding encoder = new ASCIIEncoding(); string buffer = type + ';' + message + ';' + hold + "\n"; writer.WriteUInt32(writer.MeasureString(buffer)); writer.WriteString(buffer); /* clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); * */ writer.WriteString(buffer); } catch { //Console.WriteLine("Connection Lost"); startClient(); } }
private async void OnWrite(Object sender, RoutedEventArgs e) { // 获取本地目录的引用 StorageFolder local = ApplicationData.Current.LocalFolder; // 创建新文件 StorageFile newFIle = await local.CreateFileAsync("demo.dat", CreationCollisionOption.ReplaceExisting); // 打开文件流 using(IRandomAccessStream stream = await newFIle.OpenAsync(FileAccessMode.ReadWrite)) { // 实例化 DataWriter DataWriter dw = new DataWriter(stream); // 设置默认编码格式 dw.UnicodeEncoding = UnicodeEncoding.Utf8; // 写入 bool 值 dw.WriteBoolean(true); // 写入日期值 DateTime dt = new DateTime(2010, 8, 21); dw.WriteDateTime(dt); // 写入字符串 string str = "测试文本"; // 计算字符串长度 uint len = dw.MeasureString(str); // 先写入字符串的长的 dw.WriteUInt32(len); // 再写入字符串 dw.WriteString(str); // 以下方法必须调用 await dw.StoreAsync(); // 解除 DataWriter 与流的关联 dw.DetachStream(); dw.Dispose(); } MessageDialog msgDlg = new MessageDialog("保存成功。"); await msgDlg.ShowAsync(); }
/// <summary> /// 连接并发送信息给对方 /// </summary> /// <param name="peerInformation"></param> private async void ConnectToPeer(PeerInformation peer) { dataReader = new DataReader(socket.InputStream); dataWriter = new DataWriter(socket.OutputStream); string message = "测试消息"; uint strLength = dataWriter.MeasureString(message); dataWriter.WriteUInt32(strLength); dataWriter.WriteString(message); uint numBytesWritten = await dataWriter.StoreAsync(); }
public async void sendMail(string strSendTo,string strContent , Boolean hasPicture) { HostName hostName = new HostName(hostIP); StreamSocket socket = new StreamSocket(); List<string[]> storeList = new List<string[]>(); try { await socket.ConnectAsync(hostName, port); } catch (Exception exception) { if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } } StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("Temp"); StorageFile pic = await folder.GetFileAsync("MyPainter.png"); IBuffer buffer = await FileIO.ReadBufferAsync(pic); DataWriter writer = new DataWriter(socket.OutputStream); writer.WriteUInt32(writer.MeasureString(strSendTo)); writer.WriteString(strSendTo); writer.WriteUInt32(writer.MeasureString(strContent)); writer.WriteString(strContent); if (hasPicture) { writer.WriteUInt32((uint)buffer.Length); writer.WriteBuffer(buffer); } else { writer.WriteUInt32(0); writer.WriteString(""); } await writer.StoreAsync(); writer.DetachStream(); writer.Dispose(); socket.Dispose(); }
void InitializeServiceSdpAttributes(RfcommServiceProvider provider) { Windows.Storage.Streams.DataWriter writer = new Windows.Storage.Streams.DataWriter(); // First write the attribute type writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE); // Then write the data writer.WriteUInt32(MINIMUM_SERVICE_VERSION); IBuffer data = writer.DetachBuffer(); provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data); }
/// <summary> /// Send a message to the server. /// This message is specified in the JsonObject message. /// The byteorder of the send message is LittleEndian and the encoding is Utf8. /// </summary> /// <param name="message">The message to be send.</param> /// <returns>A boolean that indicates that the message was succesfully send.</returns> public async Task <bool> SendMessage(JsonObject message) { //Check if the connector is connected. If not, call the Connect() function. if (!isConnected) { await Connect(); } //Write the message to the server. //Code used from https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.datawriter try { using (var dataWriter = new Windows.Storage.Streams.DataWriter(socket.OutputStream)) { dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; // Parse the input stream and write each element separately. //Get the string version of the json object. var stringToSend = message.ToString(); //Get the length of the stream, so the server knows how much data was send. uint inputElementSize = dataWriter.MeasureString(stringToSend); dataWriter.WriteUInt32(inputElementSize); dataWriter.WriteString(stringToSend); Debug.WriteLine("Wrote" + stringToSend); Debug.WriteLine("Lenght:" + inputElementSize); // Send the contents of the writer to the backing stream. await dataWriter.StoreAsync(); // For the in-memory stream implementation we are using, the flushAsync call // is superfluous,but other types of streams may require it. await dataWriter.FlushAsync(); // In order to prolong the lifetime of the stream, detach it from the // DataWriter so that it will not be closed when Dispose() is called on // dataWriter. Were we to fail to detach the stream, the call to // dataWriter.Dispose() would close the underlying stream, preventing // its subsequent use by the DataReader below. dataWriter.DetachStream(); return(true); } } catch { //TODO on error? throw; } }
public async void WriteToSocketUsingReader(IBuffer buffer) { using (var dataWriter = new Windows.Storage.Streams.DataWriter(socket.OutputStream)) { dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; dataWriter.WriteUInt32(buffer.Length); dataWriter.WriteBuffer(buffer); await dataWriter.StoreAsync(); await dataWriter.FlushAsync(); dataWriter.DetachStream(); } }
private async void Button_Click(object sender, RoutedEventArgs e) { string message = txtSend.Text; DataWriter writer = new DataWriter(socket.OutputStream); var length = writer.MeasureString(message); writer.WriteUInt32(length); //将字符串写入流中 writer.WriteString(message); //向服务器发送数据 await writer.StoreAsync(); await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { textList.Items.Add(message); }); }
async void streamSocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { int i = 0; DataReader dataReader = new DataReader(args.Socket.InputStream); DataWriter serverWriter = new DataWriter(args.Socket.OutputStream); try { while (true) { uint sizeCount = await dataReader.LoadAsync(4); uint length = dataReader.ReadUInt32(); uint contentLength = await dataReader.LoadAsync(length); string msg = dataReader.ReadString(contentLength); i++; Deployment.Current.Dispatcher.BeginInvoke(() => msgList.Children.Add( new TextBlock { Text = "服务器接收到的消息:" + msg })); string serverStr = msg + "|" + i; serverWriter.WriteUInt32(serverWriter.MeasureString(serverStr)); serverWriter.WriteString(serverStr); try { await serverWriter.StoreAsync(); } catch (Exception err) { if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse) { } } } } catch (Exception err) { if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse) { } } }
public async void WriteString(string HostName, string Message) { HostName remoteHostName = new HostName(HostName); using (StreamSocket socket = new StreamSocket()) { socket.Control.KeepAlive = false; await socket.ConnectAsync(remoteHostName, "6"); using (DataWriter writer = new DataWriter(socket.OutputStream)) { // set payload length writer.ByteOrder = ByteOrder.LittleEndian; writer.WriteUInt32(writer.MeasureString(Message)); // set payload type writer.WriteByte((byte)PayloadType.String); // set payload writer.WriteString(Message); // transmit await writer.StoreAsync(); writer.DetachStream(); } using (DataReader reader = new DataReader(socket.InputStream)) { int length; string response; // receive payload length reader.ByteOrder = ByteOrder.LittleEndian; await reader.LoadAsync(4); length = reader.ReadInt32(); // receive payload await reader.LoadAsync((uint)length); response = reader.ReadString((uint)length); Debug.WriteLine(string.Format("response: {0}", response)); reader.DetachStream(); } } }
void InitializeServiceSdpAttributes(RfcommServiceProvider provider) { try { var writer = new Windows.Storage.Streams.DataWriter(); // First write the attribute type writer.WriteByte(Constants.SERVICE_VERSION_ATTRIBUTE_TYPE); // Then write the data writer.WriteUInt32(Constants.SERVICE_VERSION); var data = writer.DetachBuffer(); provider.SdpRawAttributes.Add(Constants.SERVICE_VERSION_ATTRIBUTE_ID, data); //Check attributes try { var attributes = provider.SdpRawAttributes; // BluetoothCacheMode.Uncached); var attribute = attributes[Constants.SERVICE_VERSION_ATTRIBUTE_ID]; var reader = DataReader.FromBuffer(attribute); // The first byte contains the attribute' s type byte attributeType = reader.ReadByte(); if (attributeType == Constants.SERVICE_VERSION_ATTRIBUTE_TYPE) { // The remainder is the data uint version = reader.ReadUInt32(); bool ret = (version >= Constants.MINIMUM_SERVICE_VERSION); } } catch (Exception ex) { PostMessage("OBEX_Recv.InitializeServiceSdpAttributes_Check", ex.Message); } } catch (Exception ex) { PostMessage("OBEX_Receiver.InitializeServiceSdpAttributes", ex.Message); } }
private async void TcpService_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { using (var client = args.Socket) using (var dr = new DataReader(client.InputStream)) using (var dw = new DataWriter(client.OutputStream)) { await dr.LoadAsync(sizeof(Int32)); var messageLenght = dr.ReadUInt32(); await dr.LoadAsync(messageLenght); var bytes = new Byte[messageLenght]; dr.ReadBytes(bytes); var request = Encoding.UTF8.GetString(bytes); var response = "Успешно получено"; var body = Encoding.UTF8.GetBytes(response); dw.WriteUInt32((UInt32)body.Length); dw.WriteBytes(body); await dw.StoreAsync(); } }
public static async void SaveTo ( ObservableCollection<RecentData> datas ) { StorageFile sf = await ApplicationData.Current.LocalFolder.CreateFileAsync ( "data.dat", Windows.Storage.CreationCollisionOption.ReplaceExisting ); FileRandomAccessStream stream = await sf.OpenAsync ( FileAccessMode.ReadWrite ) as FileRandomAccessStream; DataWriter dw = new DataWriter ( stream ); dw.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; dw.ByteOrder = ByteOrder.LittleEndian; dw.WriteInt32 ( datas.Count ); foreach ( RecentData data in datas ) { dw.WriteUInt32 ( ( uint ) dw.MeasureString ( data.Source ) ); dw.WriteString ( data.Source ); dw.WriteInt32 ( data.SourceIndex ); dw.WriteInt32 ( data.TargetIndex ); } await dw.StoreAsync (); await dw.FlushAsync (); stream.Dispose (); }
public async void Reboot(string HostName) { HostName remoteHostName = new HostName(HostName); using (StreamSocket socket = new StreamSocket()) { socket.Control.KeepAlive = false; await socket.ConnectAsync(remoteHostName, "6"); using (DataWriter writer = new DataWriter(socket.OutputStream)) { // set payload length writer.ByteOrder = ByteOrder.LittleEndian; writer.WriteUInt32(2); // set payload type writer.WriteByte((byte)PayloadType.Byte); // set payload writer.WriteByte(0x01); // transmit await writer.StoreAsync(); writer.DetachStream(); } } }
private async void SendSocket_Click(object sender, RoutedEventArgs e) { using (var socket = new StreamSocket()) using (var dw = new DataWriter(socket.OutputStream)) using (var dr = new DataReader(socket.InputStream)) { var end = new EndpointPair( localHostName: new HostName("localhost"), localServiceName: String.Empty, remoteHostName: new HostName("localhost"), remoteServiceName: "50000"); //await socket.ConnectAsync(new HostName("localhost"), "8080"); await socket.ConnectAsync(end); var message = Message.Text; var body = Encoding.UTF8.GetBytes(message); dw.WriteUInt32((UInt32)body.Length); dw.WriteBytes(body); await dw.StoreAsync(); await dr.LoadAsync(sizeof(Int32)); var response = dr.ReadString(100); } }
private async Task InternalSendMessage(Command cmd, DataWriter writer) { if(cmd == null) { return; } if(cmd.Program == GlowPrograms.None) { throw new Exception("The program can't be none!"); } // Serialize the cmd string cmdJson = Newtonsoft.Json.JsonConvert.SerializeObject(cmd); UInt32 stringSize = writer.MeasureString(cmdJson); writer.WriteUInt32(stringSize); writer.WriteString(cmdJson); await writer.StoreAsync(); }
public async void Send(string s) { if (deviceService != null) { //send data string sendData = s; if (string.IsNullOrEmpty(sendData)) { //errorStatus.Visibility = Visibility.Visible; errorStatusText = "Please specify the string you are going to send"; Debug.WriteLine("CommunicationChannelBT: " + errorStatusText); } else { DataWriter dwriter = new DataWriter(streamSocket.OutputStream); UInt32 len = dwriter.MeasureString(sendData); dwriter.WriteUInt32(len); dwriter.WriteString(sendData); await dwriter.StoreAsync(); await dwriter.FlushAsync(); } } else { //errorStatus.Visibility = Visibility.Visible; errorStatusText = "Bluetooth is not connected correctly!"; Debug.WriteLine("CommunicationChannelBT: " + errorStatusText); } }
private void btnAddIe_Click(object sender, RoutedEventArgs e) { if (_publisher == null) { _publisher = new WiFiDirectAdvertisementPublisher(); } if (txtInformationElement.Text == "") { rootPage.NotifyUser("Please specifiy an IE", NotifyType.ErrorMessage); return; } WiFiDirectInformationElement IE = new WiFiDirectInformationElement(); // IE blob DataWriter dataWriter = new DataWriter(); dataWriter.UnicodeEncoding = UnicodeEncoding.Utf8; dataWriter.ByteOrder = ByteOrder.LittleEndian; dataWriter.WriteUInt32(dataWriter.MeasureString(txtInformationElement.Text)); dataWriter.WriteString(txtInformationElement.Text); IE.Value = dataWriter.DetachBuffer(); // OUI DataWriter dataWriterOUI = new DataWriter(); dataWriterOUI.WriteBytes(Globals.CustomOui); IE.Oui = dataWriterOUI.DetachBuffer(); // OUI Type IE.OuiType = Globals.CustomOuiType; _publisher.Advertisement.InformationElements.Add(IE); txtInformationElement.Text = ""; rootPage.NotifyUser("IE added successfully", NotifyType.StatusMessage); }
private void btnAddIe_Click(object sender, RoutedEventArgs e) { WiFiDirectInformationElement informationElement = new WiFiDirectInformationElement(); // Information element blob DataWriter dataWriter = new DataWriter(); dataWriter.UnicodeEncoding = UnicodeEncoding.Utf8; dataWriter.ByteOrder = ByteOrder.LittleEndian; dataWriter.WriteUInt32(dataWriter.MeasureString(txtInformationElement.Text)); dataWriter.WriteString(txtInformationElement.Text); informationElement.Value = dataWriter.DetachBuffer(); // Organizational unit identifier (OUI) informationElement.Oui = CryptographicBuffer.CreateFromByteArray(Globals.CustomOui); // OUI Type informationElement.OuiType = Globals.CustomOuiType; // Save this information element so we can add it when we advertise. _informationElements.Add(informationElement); txtInformationElement.Text = ""; rootPage.NotifyUser("IE added successfully", NotifyType.StatusMessage); }
private async void OnPerformAction() { var stream = socket.OutputStream; using (var writer = new DataWriter(stream)) { writer.ByteOrder = ByteOrder.LittleEndian; //writer.WriteInt16(6); //writer.WriteByte(0x00); //writer.WriteByte(3); //writer.WriteUInt16(1500); //writer.WriteUInt16(1000); //var bytes = new byte[] { 6, 0, 0, 3, 220, 5, 232, 3 }; //writer.WriteBytes(bytes); writer.WriteInt16(12); writer.WriteByte(Byte0); writer.WriteByte(Byte1); writer.WriteByte(Byte2); writer.WriteByte(Byte3); writer.WriteByte(Byte4); writer.WriteByte(Byte5); writer.WriteByte(Byte6); writer.WriteByte(Byte7); writer.WriteUInt32(FourBytes); await writer.StoreAsync(); writer.DetachStream(); } using (var reader = new DataReader(socket.InputStream)) { reader.ByteOrder = ByteOrder.LittleEndian; await reader.LoadAsync(5); var length = reader.ReadUInt16(); var byte1 = reader.ReadByte(); var byte2 = reader.ReadByte(); var status = reader.ReadByte(); reader.DetachStream(); } }
public async Task SendMessageAsync(string deviceId, string message) { RfcommDeviceService messageService = await RfcommDeviceService.FromIdAsync(deviceId); int result = await ValidateConnection(messageService); if (result != 0) return; StreamSocket messageSocket; lock (this) { messageSocket = new StreamSocket(); } try { await messageSocket.ConnectAsync(messageService.ConnectionHostName, messageService.ConnectionServiceName); DataWriter messageWriter = new DataWriter(messageSocket.OutputStream); messageWriter.WriteUInt32((uint)message.Length); messageWriter.WriteString(message); await messageWriter.StoreAsync(); } catch (Exception) { throw; } }
private async void send_Click(object sender, RoutedEventArgs e) { j++; serverWriter = new DataWriter(socket.OutputStream); string serverStr = "cilent test "+j ; serverWriter.WriteUInt32(serverWriter.MeasureString(serverStr)); serverWriter.WriteString(serverStr); try { await serverWriter.StoreAsync(); msgList.Children.Add( new TextBlock { Text = "客户端发送的消息:" + serverStr }); } catch (Exception err) { if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse) { } } }
private async Task sendMessage(string message) { if (datagramSocket == null) { this.OutputTextblock.Text += "No connection found\n"; return; } var outputstream = await datagramSocket.GetOutputStreamAsync(datagramSocket.Information.RemoteAddress, datagramSocket.Information.RemotePort); DataWriter datawritter = new DataWriter(outputstream); datawritter.WriteUInt32(datawritter.MeasureString(message)); // Ghi chuỗi datawritter.WriteString(message); try { // Gửi Socket đi await datawritter.StoreAsync(); // Xuất thông tin ra màn hình bằng textbox this.OutputTextblock.Text += "Send from " + datagramSocket.Information.LocalAddress + ": " + message + "\n"; } catch (Exception ex) { this.OutputTextblock.Text += ex.Message + "\n"; } }
public async void ConnectAsync(string host, string name) { HostName hostName; try { hostName = new HostName(host); } catch (ArgumentException) { Debug.WriteLine("Error: Invalid host name {0}.", host); return; } _socket = new StreamSocket(); _socket.Control.KeepAlive = true; _socket.Control.QualityOfService = SocketQualityOfService.LowLatency; //hard coded port - can be user-specified but to keep this sample simple it is 21121 await _socket.ConnectAsync(hostName, "21121"); Debug.WriteLine("Connected"); //first message to send is the name of this virtual speaker _writer = new DataWriter(_socket.OutputStream); _writer.WriteUInt32(_writer.MeasureString(name)); _writer.WriteString(name); try { await _writer.StoreAsync(); Debug.WriteLine("{0} registered successfully.", name); } catch (Exception exception) { Debug.WriteLine("Send failed with error: " + exception.Message); // If this is an unknown status it means that the error if fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } } //set no current message type MessageType currentMessageType = MessageType.Unknown; // then wait for the audio to be sent to us DataReader reader = new DataReader(_socket.InputStream); while (true) { uint x = await reader.LoadAsync(sizeof(short)); short t = reader.ReadInt16(); currentMessageType = (MessageType)t; switch (currentMessageType) { case MessageType.Media: await ReadMediaFileAsync(reader); break; case MessageType.Play: { MediaPlayer mediaPlayer = BackgroundMediaPlayer.Current; if (mediaPlayer != null) { if (mediaPlayer.CurrentState != MediaPlayerState.Playing) { mediaPlayer.SetStreamSource(_playingStream); mediaPlayer.Play(); Debug.WriteLine("Player playing. TotalDuration = " + mediaPlayer.NaturalDuration.Minutes + ':' + mediaPlayer.NaturalDuration.Seconds); } } } break; case MessageType.Stop: { MediaPlayer mediaPlayer = BackgroundMediaPlayer.Current; if (mediaPlayer != null) { if (mediaPlayer.CurrentState == MediaPlayerState.Playing) { mediaPlayer.Pause(); Debug.WriteLine("Player paused"); } } } break; default: break; } currentMessageType = MessageType.Unknown; } }
public async void SendData(string message) { if (_streamSocket == null || string.IsNullOrEmpty(message)) { return; } try { DataWriter dwriter = new DataWriter(_streamSocket.OutputStream); UInt32 len = dwriter.MeasureString(message); dwriter.WriteUInt32(len); dwriter.WriteString(message); await dwriter.StoreAsync(); await dwriter.FlushAsync(); } catch (Exception ex) { if (ObexErrorCallback != null) { ObexErrorCallback("Sending data from Bluetooth encountered error!" + ex.Message); } } }
private async Task InitBrowseWpToWin() { provider = await RfcommServiceProvider.CreateAsync( RfcommServiceId.FromUuid(rfcommServiceUuid)); var listener = new StreamSocketListener(); listener.ConnectionReceived += HandleConnectionReceived; await listener.BindServiceNameAsync( provider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); using (var writer = new DataWriter()) { writer.WriteByte(ServiceVersionAttributeType); writer.WriteUInt32(ServiceVersion); var data = writer.DetachBuffer(); provider.SdpRawAttributes.Add(ServiceVersionAttributeId, data); provider.StartAdvertising(listener); } }
void InitializeServiceSdpAttributes(RfcommServiceProvider provider) { var writer = new Windows.Storage.Streams.DataWriter(); // First write the attribute type writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE); // Then write the data writer.WriteUInt32(SERVICE_VERSION); var data = writer.DetachBuffer(); provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data); }
private async Task sendMessage(string message) { if (_streamsocket == null) { this.textboxDebug.Text += "No connection found\n"; return; } DataWriter datawritter = new DataWriter(_streamsocket.OutputStream); // cấu trúc dữ liệu gởi đi gồm // [độ dài chuỗi]_[chuỗi] // có độ dài chuỗi đễ dễ đọc. // Ghi độ dài chuỗi datawritter.WriteUInt32(datawritter.MeasureString(message)); // Ghi chuỗi datawritter.WriteString(message); try { // Gửi Socket đi await datawritter.StoreAsync(); // Xuất thông tin ra màn hình bằng textbox this.textboxDebug.Text += "Send from " + _streamsocket.Information.LocalAddress + ": " + message + "\n"; } catch (Exception ex) { this.textboxDebug.Text += ex.Message + "\n"; } }
private static async Task Send(StreamSocket socket, object data) { if (socket != null) { using (var writer = new DataWriter(socket.OutputStream)) { var str = Transport.Serialize(data); writer.WriteUInt32(writer.MeasureString(str)); writer.WriteString(str); try { await writer.StoreAsync(); //await writer.FlushAsync(); } catch (Exception exception) { // If this is an unknown status it means that the error if fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } } writer.DetachStream(); } await socket.CancelIOAsync(); socket.Dispose(); } }
public async Task SendFileAsync(string deviceId, IReadOnlyList<IStorageItem> storageItems) { // right now just supporting delivering just one file if (storageItems.Count == 0) return; StorageFile storageFile = (StorageFile)storageItems.First(); RfcommDeviceService messageService = await RfcommDeviceService.FromIdAsync(deviceId); int result = await ValidateConnection(messageService); if (result != 0) return; StreamSocket messageSocket; lock (this) { messageSocket = new StreamSocket(); } try { await messageSocket.ConnectAsync(messageService.ConnectionHostName, messageService.ConnectionServiceName); using (DataWriter messageWriter = new DataWriter(messageSocket.OutputStream)) { //var prop = await storageFile.GetBasicPropertiesAsync(); //// send file name length //messageWriter.WriteInt32(storageFile.Name.Length); //// send the file name //messageWriter.WriteString(storageFile.Name); //// send the file length //messageWriter.WriteUInt64(prop.Size); //// send the file //var fileStream = await storageFile.OpenAsync(FileAccessMode.Read); //Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer((uint)prop.Size); //await fileStream.ReadAsync(buffer, (uint)prop.Size, InputStreamOptions.None); //messageWriter.WriteBuffer(buffer); string text = DateTime.Now.ToString(); messageWriter.WriteUInt32((uint)text.Length); await messageWriter.StoreAsync(); messageWriter.WriteString(text); //await messageWriter.StoreAsync(); //messageWriter.WriteUInt32((uint)buffer.Length); //await messageWriter.StoreAsync(); //messageWriter.WriteBuffer(buffer); await messageWriter.FlushAsync(); await messageWriter.StoreAsync(); await messageSocket.OutputStream.FlushAsync(); } } catch (Exception) { throw; } finally { //messageSocket.Dispose(); } }
private async void ChangeLedState(int ledNum, State state) { using (StreamSocket socket = new StreamSocket()) { HostName host = new HostName("192.168.1.196"); try { await socket.ConnectAsync(host, "5656"); using (DataWriter writer = new DataWriter(socket.OutputStream)) { string stringToSend = String.Format("{0}, {1}", ledNum, state); writer.WriteUInt32(writer.MeasureString(stringToSend)); writer.WriteString(stringToSend); await writer.StoreAsync(); } } catch (Exception exception) { // If this is an unknown status it means that the error if fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } } } }
private async void SendData_Click(object sender, RoutedEventArgs e) { if (deviceService != null) { //send data string sendData = messagesent.Text; if (string.IsNullOrEmpty(sendData)) { errorStatus.Visibility = Visibility.Visible; errorStatus.Text = "Please specify the string you are going to send"; } else { DataWriter dwriter = new DataWriter(streamSocket.OutputStream); UInt32 len = dwriter.MeasureString(sendData); dwriter.WriteUInt32(len); dwriter.WriteString(sendData); await dwriter.StoreAsync(); await dwriter.FlushAsync(); } } else { errorStatus.Visibility = Visibility.Visible; errorStatus.Text = "Bluetooth is not connected correctly!"; } }