async Task NetworkStreamHandler(TcpClient client) { while (client.Connected) { var stream = client.GetStream(); var buffer = new byte[4096]; var byteCount = await stream.ReadAsync(buffer, 0, buffer.Length); stream.Flush(); if (byteCount == 0) { break; //断线了 } var str = Encoding.UTF8.GetString(buffer, 0, byteCount); var msg = JsonUtility.FromJson <Message>(str); Debug.Log($"[播放器]收到信息 {str}"); UnitySynchronizationContext.Post(() => { if (Application.isPlaying) { EventManager.Invoke(msg); } }); } }
async Task StreamReadHandleAsync() { Debug.Log("开启数据读逻辑"); try { while (isRun && tcpClient.Connected) { var networkStream = tcpClient.GetStream(); var buffer = new byte[4096]; var byteCount = await networkStream.ReadAsync(buffer, 0, buffer.Length); if (byteCount == 0) { break; //服务器端口 } var response = Encoding.UTF8.GetString(buffer, 0, byteCount); Debug.Log($"[控制器] 接收到播放器消息 {response}!"); UnitySynchronizationContext.Post(() => EventManager.Invoke(JsonUtility.FromJson <Message>(response))); } } catch (Exception e) { UnitySynchronizationContext.Post(() => { if (message) { message.text = $"[控制器] 接收消息失败: {e}!"; } }); throw; } }
public static void Begin(string path) { context = UnitySynchronizationContext.Create(); clip = Microphone.Start("", true, ClipLengthSeconds, SamplingRate); samplesFromMicrophone = new float[clip.samples * clip.channels]; samplesInInt16 = new Int16[clip.samples * clip.channels]; sharedBuffer = Marshal.AllocCoTaskMem(clip.samples * clip.channels * 2); debugLogCallback = DebugLog; audioCallback = ReadAudio; outputResultCallback = OutputResult; set_debug_log_func(debugLogCallback); set_audio_callback(audioCallback); set_result_func(outputResultCallback); set_log_to_file("julius_log.txt"); var thread = new Thread(new ThreadStart(() => { start(path); DebugLog("Thread Finished"); })); thread.Start(); }
void SendNetMessage(string str) { try { if (null != tcpClient && tcpClient.Connected) { var networkStream = tcpClient.GetStream(); var ClientRequestBytes = Encoding.UTF8.GetBytes(str); networkStream.Write(ClientRequestBytes, 0, ClientRequestBytes.Length); networkStream.Flush(); Debug.Log($"[控制器] 发送到播放器消息 {str}!"); UnitySynchronizationContext.Post(() => { if (message) { message.text = $"[控制器] 发送到播放器消息 {str}!"; } }); } } catch (Exception e) { UnitySynchronizationContext.Post(() => { if (message) { message.text = $"[控制器] 发送消息到播放器错误 {e}!"; } }); throw; } }
public static T RunAsync <T>(Func <Task <T> > asyncMethod) { if (asyncMethod == null) { throw new ArgumentNullException("asyncMethod"); } var prevCtx = SynchronizationContext.Current; try { var syncCtx = new UnitySynchronizationContext(false); SynchronizationContext.SetSynchronizationContext(syncCtx); var t = asyncMethod(); if (t == null) { throw new InvalidOperationException("No task provided."); } t.ContinueWith(delegate { syncCtx.Complete(); }, TaskScheduler.Default); syncCtx.RunOnCurrentThread(); return(t.GetAwaiter().GetResult()); } finally { SynchronizationContext.SetSynchronizationContext(prevCtx); } }
public static UnitySynchronizationContext Create() { var context = new UnitySynchronizationContext(); SetSynchronizationContext(context); UnitySynchronizationContextRunner.Begin(context); return(context); }
public static void DoOnUnityThread(Action action) { if (Thread.CurrentThread.ManagedThreadId == UnityThreadId) { action(); } else { UnitySynchronizationContext.Post(state => action(), null); } }
public static void Begin(UnitySynchronizationContext context) { if (instance != null) { return; } var go = new GameObject("SynchronizationContextRunner"); instance = go.AddComponent <UnitySynchronizationContextRunner>(); instance.context = context; }
public static void RunOnUnityScheduler(Action action) { if (SynchronizationContext.Current == UnitySynchronizationContext) { action?.Invoke(); } else { UnitySynchronizationContext.Post(_ => action?.Invoke(), null); } }
internal void StartMonoBehaviour() { if (FirebaseHandler.firebaseHandler == null) { FirebaseHandler.firebaseHandler = this; } GameObject gameObject = new GameObject("Firebase Services"); FirebaseHandler.firebaseMonoBehaviour = gameObject.AddComponent <FirebaseMonoBehaviour>(); UnitySynchronizationContext.Create(gameObject); UnityEngine.Object.DontDestroyOnLoad(gameObject); }
private void Awake() { if (Instance != null) { throw new NotSupportedException("UnityScheduler already exists."); } Instance = this; MainThreadId = Thread.CurrentThread.ManagedThreadId; DontDestroyOnLoad(gameObject); synchronizationContext = new UnitySynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synchronizationContext); }
private void Awake() { if (Instance != null) { throw new NotSupportedException("UnityScheduler already exists."); } Instance = this; MainThreadId = Thread.CurrentThread.ManagedThreadId; DontDestroyOnLoad(gameObject); synchronizationContext = new UnitySynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synchronizationContext); }
internal void StopMonoBehaviour() { if (FirebaseHandler.firebaseMonoBehaviour != null) { FirebaseHandler.RunOnMainThread <bool>(delegate { if (FirebaseHandler.firebaseMonoBehaviour != null) { UnitySynchronizationContext.Destroy(); UnityEngine.Object.Destroy(FirebaseHandler.firebaseMonoBehaviour.gameObject); } return(true); }); } }
public ClubPenguinClient(MonoBehaviour monoBehaviour, string apiURL, string clientToken, string clientApiVersion, string gameZone, bool gameEncryption, bool gameDebugging, bool lagMonitoring, int gameServerLatencyWindowSize, int webServiceLatencyWindowSize, string cpMonitoringURL, string websiteApiURL, bool offlineMode) { OfflineMode = offlineMode; SyncContext = new UnitySynchronizationContext(monoBehaviour); ICommonGameSettings commonGameSettings = Service.Get <ICommonGameSettings>(); if (offlineMode && string.IsNullOrEmpty(commonGameSettings.GameServerHost) && string.IsNullOrEmpty(commonGameSettings.CPAPIServicehost)) { GameServer = new OfflineGameServerClient(this); } else { GameServer = new SmartFoxGameServerClient(this, gameZone, gameEncryption, gameDebugging, lagMonitoring); } BreadcrumbApi = new BreadcrumbApi(this); ChatApi = new ChatApi(this); ConsumableApi = new ConsumableApi(this); DurableApi = new DurableApi(this); EncryptionApi = new EncryptionApi(this); GameApi = new GameApi(this); IglooApi = new IglooApi(this); InventoryApi = new InventoryApi(this); MinigameApi = new MinigameApi(this); PlayerApi = new PlayerApi(this); QuestApi = new QuestApi(this); RewardApi = new RewardApi(this); SavedOutfitApi = new SavedOutfitApi(this); TaskApi = new TaskApi(this); IAPApi = new IAPApi(this); TutorialApi = new TutorialApi(this); ModerationApi = new ModerationApi(this); TubeApi = new TubeApi(this); DisneyStoreApi = new DisneyStoreApi(this); NewsfeedApi = new NewsfeedApi(this); CatalogApi = new CatalogApi(this); ScheduledEventApi = new ScheduledEventApi(this); DiagnosticsApi = new DiagnosticsApi(this); CaptchaApi = new CaptchaApi(this); initWAK(apiURL, clientToken, clientApiVersion); Configuration.SetBaseUri("cp-monitoring-base-uri", cpMonitoringURL); Configuration.SetBaseUri("cp-website-api-base-uri", websiteApiURL); initCPKeyValueDatabase(Service.Get <IKeychain>()); initEncryption(); RecoverableOperationService = new QueuableRecoverableOperationService(this); if (lagMonitoring) { GameServerLatency = new RollingStatistics(gameServerLatencyWindowSize); WebServiceLatency = new RollingStatistics(webServiceLatencyWindowSize); } }
private async Task ConnectAsTcpClient() { isRun = true; tcpClient = new TcpClient(); tcpClient.NoDelay = true; try { await tcpClient.ConnectAsync("127.0.0.1", 8888); } catch (Exception e) { message.text = $"[控制器] 连接到播放器失败 {e}!"; throw; } UnitySynchronizationContext.Post(() => message.text = "[控制器] 连接到播放器!"); var _ = Task.Run(StreamReadHandleAsync); }
public static void RunAsync(Action asyncMethod) { if (asyncMethod == null) { throw new ArgumentNullException("asyncMethod"); } var prevCtx = SynchronizationContext.Current; try { var syncCtx = new UnitySynchronizationContext(true); SynchronizationContext.SetSynchronizationContext(syncCtx); syncCtx.OperationStarted(); asyncMethod(); syncCtx.OperationCompleted(); syncCtx.RunOnCurrentThread(); } finally { SynchronizationContext.SetSynchronizationContext(prevCtx); } }
void SendNetMessage(string str) { try { if (isRun) { var networkStream = tcpClient.GetStream(); var data = Encoding.UTF8.GetBytes(str); byte[] size = BytesHelper.GetBytes((ushort)data.Length); var temp = new byte[size.Length + data.Length]; Buffer.BlockCopy(size, 0, temp, 0, size.Length); Buffer.BlockCopy(data, 0, temp, size.Length, data.Length); networkStream.Write(temp, 0, temp.Length); networkStream.Flush(); Debug.Log($"[控制器] 发送到播放器消息 {str}!"); UnitySynchronizationContext.Post(() => { if (message) { message.text = $"[控制器] 发送到播放器消息 {str}!"; } }); } else { Debug.LogWarning($"{nameof(PlayerController)}: 已经与服务器断开连接!"); } } catch (Exception e) { UnitySynchronizationContext.Post(() => { if (message) { message.text = $"[控制器] 发送消息到播放器错误 {e}!"; } }); throw; } }
public SynchronizationContextAwaiter(UnitySynchronizationContext context) { this.context = context; }
public SynchronizationContextAwaiter(UnitySynchronizationContext context) { this.context = context; }
public static IHttpRequest CreateHttpRequest(UnitySynchronizationContext defaultSyncContext) { return(new HttpRequest()); }
public UnityTaskScheduler(string name) { Name = name; Context = new UnitySynchronizationContext(name); }
public UnityTaskScheduler(string name) { Name = name; Context = new UnitySynchronizationContext(name); }