本文整理汇总了C#中Windows.Storage.Streams.DataWriter.MeasureString方法的典型用法代码示例。如果您正苦于以下问题:C# DataWriter.MeasureString方法的具体用法?C# DataWriter.MeasureString怎么用?C# DataWriter.MeasureString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Storage.Streams.DataWriter
的用法示例。
在下文中一共展示了DataWriter.MeasureString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: OnWrite
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();
}
示例2: send
/// <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();
}
}
示例3: ConnectToPeer
/// <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();
}
示例4: sendMail
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();
}
示例5: Button_Click
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);
});
}
示例6: streamSocketListener_ConnectionReceived
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)
{
}
}
}
示例7: WriteString
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();
}
}
}
示例8: SaveTo
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 ();
}
示例9: Send
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);
}
}
示例10: btnAddIe_Click
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);
}
示例11: sendMessage
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";
}
}
示例12: ConnectAsync
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;
}
}
示例13: send_Click
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)
{
}
}
}
示例14: SendMessage
// Отправка сообщения
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();
}
示例15: Send
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();
}