private void OnConnected(IAsyncAction asyncinfo, AsyncStatus asyncstatus) { lock (this.syncer) { if (asyncinfo.AsTask().IsCompleted&& !asyncinfo.AsTask().IsFaulted&& this.sock != null && this.sock.Information.RemoteAddress != null) { this.PingBytes[this.PingBytes.Length - 1] = this.PingId; DataWriter writer; writer = new DataWriter(this.sock.OutputStream); writer.WriteBytes(this.PingBytes); DataWriterStoreOperation res = writer.StoreAsync(); res.AsTask().Wait(100); this.PingBytes[this.PingBytes.Length - 1] = (byte)(this.PingId + 1); // this buffer is re-used for the result/receive. invalidate the result now. writer.DetachStream(); writer.Dispose(); } else { this.sock = null; // will cause Done() to return true but this.Successful defines if the roundtrip completed } } }
// Only included if HoloLens #if !UNITY_EDITOR && UNITY_WSA_10_0 /// <summary> /// Called when the async action is completed (establishing a connection within SendMesh(string networkConfig)) /// If connection is successful, write the Room Mesh data from the Database to the network connection /// If connection is unsuccessful, dispose of the client (StreamSocket) /// </summary> /// <param name="asyncInfo">Information about the async action</param> /// <param name="status">The current status of the async action</param> public void NetworkConnectedHandler(IAsyncAction asyncInfo, AsyncStatus status) { //Debug.Log("YOU CONNECTED TO: " + networkConnection.Information.RemoteAddress.ToString()); // Status completed is successful. if (status == AsyncStatus.Completed) { Debug.Log("PREPARING TO WRITE DATA..."); DataWriter networkDataWriter; // Since we are connected, we can send the data we set aside when establishing the connection. using (networkDataWriter = new DataWriter(holoClient.OutputStream)) { Debug.Log("PREPARING TO WRITE DATA"); // Then write the data. // networkDataWriter.WriteBytes(Database.GetMeshAsBytes()); // Again, this is an async operation, so we'll set a callback. DataWriterStoreOperation dswo = networkDataWriter.StoreAsync(); dswo.Completed = new AsyncOperationCompletedHandler <uint>(DataSentHandler); } } else { Debug.LogWarning("Failed to establish connection. Error Code: " + asyncInfo.ErrorCode); // In the failure case we'll requeue the data and wait before trying again. holoClient.Dispose(); } }
public void WriteAllText(string filename, string text, Action completed) { StorageFolder localFolder = ApplicationData.Current.LocalFolder; IAsyncOperation <StorageFile> createOp = localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); createOp.Completed = (asyncInfo1, asyncStatus1) => { IStorageFile storageFile = asyncInfo1.GetResults(); IAsyncOperation <IRandomAccessStream> openOp = storageFile.OpenAsync(FileAccessMode.ReadWrite); openOp.Completed = (asyncInfo2, asyncStatus2) => { IRandomAccessStream stream = asyncInfo2.GetResults(); DataWriter dataWriter = new DataWriter(stream); dataWriter.WriteString(text); DataWriterStoreOperation storeOp = dataWriter.StoreAsync(); storeOp.Completed = (asyncInfo3, asyncStatus3) => { dataWriter.Dispose(); completed(); }; }; }; }
/// <summary> /// Called when a connection attempt complete, successfully or not. /// !!! NOTE These do not arrive on the main Unity Thread. Most Unity operations will throw in the callback !!! /// </summary> /// <param name="asyncInfo">Data about the async operation.</param> /// <param name="status">The status of the operation.</param> public void NetworkConnectedHandler(IAsyncAction asyncInfo, AsyncStatus status) { // Status completed is successful. if (status == AsyncStatus.Completed) { DataWriter networkDataWriter; // Since we are connected, we can send the data we set aside when establishing the connection. using (networkDataWriter = new DataWriter(networkConnection.OutputStream)) { // Write how much data we are sending. networkDataWriter.WriteInt32(nextDataBufferToSend.Length); // Then write the data. networkDataWriter.WriteBytes(nextDataBufferToSend); // Again, this is an async operation, so we'll set a callback. DataWriterStoreOperation dswo = networkDataWriter.StoreAsync(); dswo.Completed = new AsyncOperationCompletedHandler <uint>(DataSentHandler); } } else { Debug.Log("Failed to establish connection. Error Code: " + asyncInfo.ErrorCode); // In the failure case we'll requeue the data and wait before trying again. networkConnection.Dispose(); // Didn't send, so requeue the data. dataQueue.Enqueue(nextDataBufferToSend); // And set the defer time so the update loop can do the 'Unity things' // on the main Unity thread. deferTime = timeToDeferFailedConnections; } }
public void NetworkConnectedHandler(IAsyncAction asyncInfo, AsyncStatus status) { DataWriter networkDataWriter; // Status completed is successful. if (status == AsyncStatus.Completed) { // Since we are connected, we can send the data we set aside when establishing the connection. using (networkDataWriter = new DataWriter(socket2.OutputStream)) { Debug.Log("Sending " + stringToSend + " to " + strhostname + " at port " + strport); //networkDataWriter.WriteUInt32(networkDataWriter.MeasureString(stringToSend)); //networkDataWriter.WriteString(stringToSend); if (stringToSend == "1") { networkDataWriter.WriteByte(1); } else if (stringToSend == "2") { networkDataWriter.WriteByte(2); } else if (stringToSend == "3") { networkDataWriter.WriteByte(3); } else if (stringToSend == "4") { networkDataWriter.WriteByte(4); } else if (stringToSend == "5") { networkDataWriter.WriteByte(5); } //networkDataWriter.WriteByte(valuetosend); // Again, this is an async operation, so we'll set a callback. try { DataWriterStoreOperation dswo = networkDataWriter.StoreAsync(); dswo.Completed = new AsyncOperationCompletedHandler <uint>(DataSentHandler); Debug.Log("NetworkConnectedHandler ::Sending"); } catch (Exception exception) { Debug.Log("Store async exception"); } } } else { Debug.Log("Failed to establish connection. Error Code: " + asyncInfo.ErrorCode); // In the failure case we'll requeue the data and wait before trying again. socket2.Dispose(); } }
public float GetCurrentTime() { if (Disposed) { throw new ObjectDisposedException(this.ToString()); } OutputWriter.WriteByte(2); DataWriterStoreOperation WriteOperation = OutputWriter.StoreAsync(); WriteOperation.AsTask().Wait(); DataReaderLoadOperation ReadOperation = InputReader.LoadAsync(4); ReadOperation.AsTask().Wait(); return(InputReader.ReadSingle()); }
public (float TimeStamp, float BMPValue) GetFirstEntry() { if (Disposed) { throw new ObjectDisposedException(this.ToString()); } OutputWriter.WriteByte(1); DataWriterStoreOperation WriteOperation = OutputWriter.StoreAsync(); WriteOperation.AsTask().Wait(); DataReaderLoadOperation ReadOperation = InputReader.LoadAsync(8); ReadOperation.AsTask().Wait(); return(InputReader.ReadSingle(), InputReader.ReadSingle()); }
public ushort GetEntryCount() { if (Disposed) { throw new ObjectDisposedException(this.ToString()); } OutputWriter.WriteByte(0); DataWriterStoreOperation WriteOperation = OutputWriter.StoreAsync(); WriteOperation.AsTask().Wait(); DataReaderLoadOperation ReadOperation = InputReader.LoadAsync(2); ReadOperation.AsTask().Wait(); return(InputReader.ReadUInt16()); }
public override void Write(byte[] byteBuffer, int offset, int count) { try { CancellationTokenSource cts = new CancellationTokenSource(writeTimeout); dataWriter.WriteBuffer(byteBuffer.AsBuffer(), (uint)offset, (uint)count); DataWriterStoreOperation op = dataWriter.StoreAsync(); Task <uint> write = op.AsTask <uint>(cts.Token); write.Wait(); } catch (TaskCanceledException) { streamSocket.Dispose(); streamSocket = null; throw new TimeoutException(Resources.Timeout); } }
async Task DealRev(StreamSocket socket) { using (socket) { using (DataReader reader = new DataReader(socket.InputStream)) { try { //ShowMsg.ChangeColor(ShowMsg.MyIcons.uwb); while (true) { await reader.LoadAsync(11); string str = reader.ReadString(11); System.Diagnostics.Debug.WriteLine(str); int num = int.Parse(str.Split(':')[1]); switch (str.Substring(0, 3)) { case "1 2": d12 = num; break; case "1 3": d13 = num; break; case "1 4": d14 = num; break; case "2 3": d23 = num; break; case "2 4": d24 = num; break; case "3 4": d34 = num; break; } if (writer != null) { writer.WriteString(str); DataWriterStoreOperation operation = writer.StoreAsync(); operation.Completed = new AsyncOperationCompletedHandler <uint>(DataSendHandler); } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("ERROR---------" + e.Message); //ShowMsg.ShowMessage("UWB数据接收错误" + e.Message); } } } }
public void Save(string filename) { string text = this.Title + "\n" + this.Text; #if !WINDOWS_PHONE // iOS and Android string docsPath = Environment.GetFolderPath( Environment.SpecialFolder.Personal); string filepath = Path.Combine(docsPath, filename); File.WriteAllText(filepath, text); #else // Windows Phone StorageFolder localFolder = ApplicationData.Current.LocalFolder; IAsyncOperation <StorageFile> createOp = localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); createOp.Completed = (asyncInfo1, asyncStatus1) => { IStorageFile storageFile = asyncInfo1.GetResults(); IAsyncOperation <IRandomAccessStream> openOp = storageFile.OpenAsync(FileAccessMode.ReadWrite); openOp.Completed = (asyncInfo2, asyncStatus2) => { IRandomAccessStream stream = asyncInfo2.GetResults(); DataWriter dataWriter = new DataWriter(stream); dataWriter.WriteString(text); DataWriterStoreOperation storeOp = dataWriter.StoreAsync(); storeOp.Completed = (asyncInfo3, asyncStatus3) => { dataWriter.Dispose(); }; }; }; #endif }
public bool Send(byte[] buffer) { try { _dataWriter.WriteBytes(buffer); _dataWriterOperation = _dataWriter.StoreAsync(); _dataWriterOperation.AsTask().Wait(); if (_dataWriterOperation.ErrorCode != null) { OnErrorOccured(new SocketErrorEventArgs(SocketErrorEventArgs.SocketMethod.Connect, SocketError.GetStatus(_dataWriterOperation.ErrorCode.HResult).ToString())); _dataWriterOperation = null; return(false); } _dataWriterOperation = null; return(true); } catch (TaskCanceledException) { return(false); } catch (Exception ex) { OnErrorOccured(new SocketErrorEventArgs(SocketErrorEventArgs.SocketMethod.Send, SocketError.GetStatus(ex.HResult).ToString())); ReCreateSocket(); return(false); } }
/// <summary> /// 发送数据 /// </summary> private void SendData(byte[] v) { try { //if (isSending) return; //UnityThread.executeInUpdate(() => { isSending = true; }); Debug.Log("准备发送"); if (writer_vstream != null) { writer_vstream.WriteInt32(v.Length); writer_vstream.WriteBytes(v); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { writer_vstream.WriteSingle(martrix_camera_to_world[i, j]); } } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { writer_vstream.WriteSingle(martrix_projection[i, j]); } } DataWriterStoreOperation operation = writer_vstream.StoreAsync(); operation.Completed = new AsyncOperationCompletedHandler <uint>(DataSentHandler); } else { Debug.Log("未与TX2建立连接,跳过本次发送"); } if (writer_pc != null) { writer_pc.WriteInt32(v.Length); writer_pc.WriteBytes(v); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (isSendWarning) { if (i == 0 && j == 0) { writer_pc.WriteSingle(100); } if (i == 0 && j == 1) { writer_pc.WriteSingle(1); isSendWarning = false; } } else { writer_pc.WriteSingle(martrix_camera_to_world[i, j]); } } } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { writer_pc.WriteSingle(martrix_projection[i, j]); } } DataWriterStoreOperation operation2 = writer_pc.StoreAsync(); operation2.Completed = new AsyncOperationCompletedHandler <uint>(DataSentHandler_PC); } else { Debug.Log("未与PC建立连接,跳过本次发送"); } } catch (Exception e) { MyLog.DebugLog(e.Message); } }