/// <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(); }
/// <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; } }
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(); } } }
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 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 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 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"; } }
// Отправка сообщения async private void SendMessage(StreamSocket socket, string message) { var writer = new DataWriter(socket.OutputStream); var len = writer.MeasureString(message); // Gets the UTF-8 string length. writer.WriteInt32((int)len); writer.WriteString(message); var ret = await writer.StoreAsync(); writer.DetachStream(); }
private async Task Send(IOutputStream outputStream, string message) { DataWriter writer = new DataWriter(outputStream); // This is useless in this sample. Just a friendly remainder. uint messageLength = writer.MeasureString(message); writer.WriteString(message); uint bytesWritten = await writer.StoreAsync(); Debug.Assert(bytesWritten == messageLength); // Do not use Dispose(). If used, streams cannot be used anymore. //writer.Dispose(); // Without this, the DataReader destructor will close the stream, and closing the // stream might set the FIN control bit. writer.DetachStream(); }
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(); }
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); }
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; } }
private async Task Send(IOutputStream outputStream, string message) { DataWriter writer = new DataWriter(outputStream); uint messageLength = writer.MeasureString(message); writer.WriteString(message); uint bytesWritten = await writer.StoreAsync(); writer.DetachStream(); }
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); } } }
// // UDP send. // private async void UdpSend_Click_1(object sender, RoutedEventArgs e) { DatagramSocket sendSocket = new DatagramSocket(); // Even when we do not except any response, this handler is called if any error occurrs. sendSocket.MessageReceived += OnMessageReceived; try { await sendSocket.ConnectAsync(new HostName("foohost"), "2704"); // DatagramSocket.ConnectAsync() vs DatagramSocket.GetOutputStreamAsync()? // Use DatagramSocket.GetOutputStreamAsync() if datagrams are sent to multiple // GetOutputStreamAsync() does DNS resolution first. // If remote host does not exist, "No such host is known. (Exception from HRESULT: 0x80072AF9)" // exception is thrown. // If remote host is not listening on the specified host, "An existing connection was forcibly // closed by the remote host. (Exception from HRESULT: 0x80072746)" exception is thrown. string message = "¡Hello, I am the new guy in the network!"; DataWriter writer = new DataWriter(sendSocket.OutputStream); // This is useless in this sample. Just a friendly remainder. uint messageLength = writer.MeasureString(message); writer.WriteString(message); uint bytesWritten = await writer.StoreAsync(); Debug.Assert(bytesWritten == messageLength); DisplayOutput(UdpSendOutput, "Message sent: " + message); } catch (Exception ex) { DisplayOutput(UdpSendOutput, ex.ToString()); } }
private async void Button_Click(object sender, RoutedEventArgs e) { if (!connected) { StatusText.Text = "Must be connected to send!"; return; } // Int32 len = 0; // Gets the UTF-8 string length. try { OutputView.Text = ""; StatusText.Text = "Trying to send data ..."; // add a newline to the text to send string sendData = SendText.Text + Environment.NewLine; DataWriter writer = new DataWriter(_clientSocket.OutputStream); UInt32 len = writer.MeasureString(sendData); // Gets the UTF-8 string length. writer.WriteString("123"); //byte[] buffer = Encoding.ASCII.GetBytes(textBox.Text); //_clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallback), null); // Call StoreAsync method to store the data to a backing stream await writer.StoreAsync(); StatusText.Text = "Data was sent" + Environment.NewLine; // detach the stream and close it writer.DetachStream(); writer.Dispose(); } catch (Exception exception) { // If this is an unknown status, // it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } StatusText.Text = "Send data or receive failed with error: " + exception.Message; // Could retry the connection, but for this simple example // just close the socket. closing = true; _clientSocket.Dispose(); _clientSocket = null; connected = false; } // Now try to receive data from server try { OutputView.Text = ""; StatusText.Text = "Trying to receive data ..."; DataReader reader = new DataReader(_clientSocket.InputStream); // Set inputstream options so that we don't have to know the data size reader.InputStreamOptions = Partial; await reader.LoadAsync(reader.UnconsumedBufferLength); } catch (Exception exception) { // If this is an unknown status, // it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } StatusText.Text = "Receive failed with error: " + exception.Message; // Could retry, but for this simple example // just close the socket. closing = true; _clientSocket.Dispose(); _clientSocket = null; connected = false; } }
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(); } }
//Envoi de la commande socket public async Task Send(string message) { DataWriter writer; // Create the data writer object backed by the in-memory stream. using (writer = new DataWriter(socket.OutputStream)) { // Set the Unicode character encoding for the output stream writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; // Specify the byte order of a stream. writer.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; // Gets the size of UTF-8 string. writer.MeasureString(message); // Write a string value to the output stream. writer.WriteString(message); // Send the contents of the writer to the backing stream. try { await writer.StoreAsync(); } catch (Exception exception) { switch (SocketError.GetStatus(exception.HResult)) { case SocketErrorStatus.HostNotFound: // Handle HostNotFound Error throw; default: // If this is an unknown status it means that the error is fatal and retry will likely fail. throw; } } await writer.FlushAsync(); // In order to prolong the lifetime of the stream, detach it from the DataWriter writer.DetachStream(); } }
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!"; } }