public void NotifyAllListener(NetworkEvent nEvent) { foreach (Listener lsn in m_listeners) { lsn.OnEvent(nEvent, this); } }
public void Init(Loading loadingScript) { mLoadingCom = loadingScript; for (int i = 0; i < mPlayerOtherMeshs.Length; i++) { if (mPlayerOtherMeshs.Length > i && mPlayerOtherMeshs[i] != null) { mPlayerOtherAnimators[i] = mPlayerOtherMeshs[i].GetComponent <Animator>(); } } for (int i = 0; i < mPlayerMeshArray.Length; i++) { if (mPlayerMeshArray.Length > i && mPlayerMeshArray[i] != null) { mPlayerAnimators[i] = mPlayerMeshArray[i].GetComponent <Animator>(); } } SetActiveLinkNameParent(false); SetAcitveStartBt(false); //SetPlayerUITexture(0); SetPlayerUIMesh(0); SetActiveUICreateSever(true); SetActiveUISeverWeiHu(false); NetworkEvent.GetInstance().OnFailedToConnectToMasterServerEvent += OnFailedToConnectToMasterServerEvent; }
// ネットワーク関連イベント受信用 public void OnNotify(Observable <NetworkEvent> observer, NetworkEvent e) { NetworkEventDispatcher dispatcher = new NetworkEventDispatcher(e); dispatcher.Dispatch <HostChengedEvent>(OnChangedHost); dispatcher.Dispatch <OtherPlayerDisconnectedEvent>(OnDisconnectOtherPlayer); }
private void HandleOnNetworkEvent(NetworkEvent e) { if (e.enumNetworkEvent == EnumNetworkEvent.GameStart) { //isGamePlaying = true; } }
internal ServerEventCapsule(NetworkEvent networkEvent, ErrorType errorType, uint userId, byte processId) { NetworkEvent = networkEvent; ErrorType = errorType; UserId = userId; ProcessId = processId; }
private void HandleIncommingMessage(ref NetworkEvent evt) { MessageDataBuffer buffer = (MessageDataBuffer)evt.MessageData; string msg = Encoding.UTF8.GetString(buffer.Buffer, 0, buffer.ContentLength); string s_dataUrlPrefix = "data:image/png;base64,"; //if server -> forward the message to everyone else including the sender if (mIsServer) { //we use the server side connection id to identify the client string idAndMessage = msg; SendString(idAndMessage); Append(idAndMessage); } else { //check for pic if (msg.StartsWith(s_dataUrlPrefix)) { ClickPic.ReceiveImage(msg); } else { //client received a message from the server -> simply print //if message received Append(msg); } } //return the buffer so the network can reuse it buffer.Dispose(); }
internal static void OnNetworkChangeCallback(NetworkEvent networkEvent) { switch (networkEvent.EventType) { case NetworkEventType.AvailabilityChanged: { if (NetworkAvailabilityChanged != null) { bool isAvailable = ((networkEvent.Flags & (byte)NetworkEventFlags.NetworkAvailable) != 0); NetworkAvailabilityEventArgs args = new NetworkAvailabilityEventArgs(isAvailable); NetworkAvailabilityChanged(null, args); } break; } case NetworkEventType.AddressChanged: { if (NetworkAddressChanged != null) { EventArgs args = new EventArgs(); NetworkAddressChanged(null, args); } break; } default: { break; } } }
/// <summary> /// Network 상태 변경 시 호출될 Callback Method /// </summary> /// <param name="status"></param> void OnStatusChanged(NetworkEvent status) { switch (status) { // 접속 성공 case NetworkEvent.connected: { LogManager.Log("on connected"); this.receivedMessage += "on connected\n"; } break; // 연결 끊김 case NetworkEvent.disconnected: { LogManager.Log("disconnected"); this.receivedMessage += "disconnected\n"; this.gameServer.Disconnect(); MySceneManager present = GameObject.Find("SceneManager").GetComponent <MySceneManager>(); if (present.Present != SceneList.Login && present.Present != SceneList.Account && present.Present != SceneList.FindUser) { present.Present = SceneList.Login; } login.Enter(); } break; } }
/// <summary> /// Notifies any observers if a networking event occurs, like a new connection opens, or data is recieved.</summary> /// <param name="netEvent">The event code specifying what function to call on the observer</param> /// <param name="ipAddr">The IP Address that the event is occuring from.</param> /// <param name="data">Any data that should be passed along to the observer.</param> /// <exception cref="ArgumentNullException">Thrown when ipAddr is null, or data is null when it is required, check exception ParamName to see which failed.</exception> private void Notify(NetworkEvent netEvent, string ipAddr, byte[] data = null) { if (ipAddr == null) { throw new ArgumentNullException("ipAddr"); } Contract.EndContractBlock(); foreach (NetObserver obs in observers) { switch (netEvent) { case NetworkEvent.CONN_OPEN: obs.ConnectionOpened(ipAddr); break; case NetworkEvent.DATA_RECV: if (data == null) { throw new ArgumentNullException("data"); } obs.DataRecieved(ipAddr, data); break; case NetworkEvent.CONN_CLOSE: obs.ConnectionClosed(ipAddr); break; default: break; } } }
public RPCEvent(INetClient client, NetworkEvent netEvent, BSONObject bson, String methodName) { this._client = client; this._netEvent = netEvent; this._bson = bson; this._methodName = methodName; }
//check the answer and update the screen public void CheckAnswer(string input) { //first we update the display letterDisplay.UpdateDisplay(input, currentWord.GetCharArray); //fetch a checkedanswer from the currentword CheckedAnswer result = currentWord.HandleSubmission(input, this); GuessedLetterCount += result.guessedLetters; //reward points and update the ui on both clients MasterManager.instance.score += result.totalPoints; NetworkEvent.UpdateUI(scoreUI, nickName + ": " + MasterManager.instance.score.ToString()); //if correct show a green flash, if not show a red flash and update the gallow if (result.correct) { fader.FadeRight(); } else { fader.FadeWrong(); NetworkEvent.UpdatePlayerGallows(MasterManager.instance.wrongAnswers, gallowUI); MasterManager.instance.wrongAnswers++; } //if the word is guessed, call the rpc to set up a new word if (WordGuessed()) { UpdateWordInGameView(); } }
/// <summary> /// 业务只需要具体实现此函数的分发即可, 此处只是简单示例 /// </summary> /// <param name="ev"></param> /// <param name="cmd"></param> /// <param name="ud"></param> /// <param name="channel"></param> public void HandleEvent(NetworkEvent ev, int cmd, NativeDataView ud, int channel) { UnityEngine.Debug.LogFormat("SampleNetworkPacketHandler.HandleEvent, event={0}, cmd={1}, channel={2}", ev, cmd, channel); if (cmd == AppProtocol.CMD_LOGIN_REQ) { // SampelScene应该是 channel:1 收到 var msg = new AppProtocol.LoginReq(); msg.decode(ud); msg.print(); // 回应客户端 var reply = new AppProtocol.LoginResp(); reply.uid = msg.uid; reply.status = 200; // 200 表示success (NativeDataView udReply, Stream hold) = reply.encode(); NetworkServiceManager.Instance.SendSerializedMsg(AppProtocol.CMD_LOGIN_RESP, udReply, AppProtocol.SERVER_CHANNEL); hold.Dispose(); } else if (cmd == AppProtocol.CMD_LOGIN_RESP) { // SampelScene应该是 channel:0 收到 // 打印登录响应消息 var msg = new AppProtocol.LoginResp(); msg.decode(ud); msg.print(); } }
public void ReceiveEvent(INetClient client, NetworkEvent netEvent, BSONObject bson) { switch (netEvent) { case NetworkEvent.ClientUpdate: if (!createFromNetworkEvent(client, netEvent, bson).isCanceled) { NetObjectManager.Obj.UpdateObjects(bson); } break; case NetworkEvent.RPC: if (!createEventFromNetworkRPCEvent(client, netEvent, bson).isCanceled) { RPCManager.HandleReceiveRPC(client, bson); } break; case NetworkEvent.RPCResponse: if (!createFromNetworkResponseEvent(client, netEvent, bson).isCanceled) { RPCManager.HandleQueryResponse(bson); } break; } }
unsafe public void OnEvent(int clientId, NetworkEvent info) { var client = m_Clients[clientId]; var type = info.type.typeId; fixed(uint *data = info.data) { var reader = new NetworkReader(data, info.type.schema); switch ((GameNetworkEvents.EventType)type) { case GameNetworkEvents.EventType.PlayerReady: m_NetworkServer.MapReady(clientId); // TODO (petera) hacky client.isReady = true; break; case GameNetworkEvents.EventType.PlayerSetup: client.playerSettings.Deserialize(ref reader); if (client.player != null) { m_serverGameWorld.HandlePlayerSetupEvent(client.player, client.playerSettings); } break; case GameNetworkEvents.EventType.RemoteConsoleCmd: HandleClientCommand(client, reader.ReadString()); break; case GameNetworkEvents.EventType.Chat: m_ChatSystem.ReceiveMessage(client, reader.ReadString(256)); break; } } }
public void ReadEvents <TInputStream>(ref TInputStream input, INetworkCallbacks networkConsumer) where TInputStream : NetworkCompression.IInputStream { //input.SetStatsType(NetworkCompressionReader.Type.Event); var numEvents = NetworkEvent.ReadEvents(eventTypesIn, connectionId, ref input, networkConsumer); counters.eventsIn += numEvents; }
public NetworkEvent Handle(Client client, NetworkEvent e) { client._ExecuteOnMainThread.RunOnMainThread.Enqueue(() => { SceneManager.LoadScene("GameScene"); }); return(null); }
/// <summary> /// 房间信息修改提示回调 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void roomInfoChangeNotifyCallBack(object sender, NetworkMessageEventArgs e) { Protocol.S2CSRoomInfoChangeNotify response = NetworkEvent.parseMessage <Protocol.S2CSRoomInfoChangeNotify>(e.message); if (response.room_id <= listView1.Items.Count) { //room id 的索引是从1开始 ListViewItem lvi = listView1.Items[(int)response.room_id - 1]; if (response.room_name != null) { lvi.SubItems[1].Text = response.room_name; } if (response.players_count != 0) { lvi.SubItems[2].Text = response.players_count.ToString(); } if (response.@public) { lvi.SubItems[3].Text = "公开"; } else { lvi.SubItems[3].Text = "不公开"; } } }
// Función de recepción de audio... private void HandleIncommingStreamingAudio(ref NetworkEvent evt) { MessageDataBuffer buffer = (MessageDataBuffer)evt.MessageData; // Se extrae el mensaje del campo de datos que llega desde la red en la variable data.... byte[] data = evt.GetDataAsByteArray(); // Los datos se pasan a float para que puedan ser reproducidos por el componente Audio Source de Unity... float[] audioData = ToFloatArray(data); // Se almacena un número de muestras de audio... for (int i = 0; i < audioData.Length; i++) { read.Add(audioData[i]); } // Cuando el número de muestras almacedanas es igual/mayor a la frecuencia, se reproducen... if (data != null && read.Count >= FREQUENCY_RATE) { AudioSource audioSource = GetComponent <AudioSource>(); speakers.SetData(read.ToArray(), 0); audioSource.clip = speakers; audioSource.Play(); read.Clear(); } //return the buffer so the network can reuse it buffer.Dispose(); }
/** * Registers a function to an event. Uses the class object name to * store multiple events from different objects. */ public void RegisterEvent(NetworkEvent eName, object eClass, Action eAction) { Debug.Assert(eName != 0, "Name is null"); Debug.Assert(eClass != null, "Type is null"); Debug.Assert(eAction != null, "Event is null"); if (!m_eventTable.TryGetValue(eName, out var value)) { value = new Dictionary <string, Action>(); } string className = eClass.GetType().Name; if (value.ContainsKey(className)) { print("Class already registered under event"); return; } value.Add(className, eAction); m_eventTable[eName] = value; print(string.Format("[ NetworkEvent ] Registered Event {0} from class {1} linked to function {2}", eName.ToString(), eClass.GetType().Name, eAction.Method.Name)); //m_eventTable.Add(eName.ToString() + eClass.GetType().Name, eAction); }
private async void Notify(ConnectionEndpoint endpoint, NetworkEvent networkEvent) { lock (this) { pendingCount++; if (pendingCount == 1) { Trace("Queue started"); syncPendingSent = new SyncEvent(); } } await Task.Delay(Parameters.CallLatency); endpoint.Notify(networkEvent); lock (this) { pendingCount--; if (pendingCount == 0) { Trace("Queue empty"); syncPendingSent.SetComplete(); } } }
private void Update() { if (netId.localPlayerOwns) { Movement(); CameraMovement(); Shooting(); if (NetworkClock.IsTimeToSend()) { netId.SendDataOverNetwork(NetworkEventType.UpdatePosition, NetworkSubeventType.Null, transform); } } else { transform.position = Vector3.Lerp(lastPos, newPos, currentLerp); currentLerp += lerpRatio; while (netId.dataQueue.Count != 0) { NetworkEvent currentData = netId.dataQueue[0]; netId.dataQueue.RemoveAt(0); if (currentData.GetNetworkEventType() == NetworkEventType.UpdatePosition) { Vector3[] newTrans = (Vector3[])currentData.GetData(); lastPos = new Vector3(newPos.x, newPos.y, newPos.z); newPos = newTrans[0]; currentLerp = lerpRatio; transform.eulerAngles = newTrans[1]; transform.localScale = newTrans[2]; } } } }
void OnNewPacket(object sender, NetworkEvent e) { this.label1.BeginInvoke((MethodInvoker)( delegate { if (this.counter != null) { this.label1.Text = "Recv: " + this.counter.RecvBytes.ToString() + " Send: " + this.counter.SentBytes.ToString() + " Total: " + this.counter.TotalBytes.ToString(); } else { this.label1.Text = e.TotalLength.ToString(); } if (this.counter2 != null) { this.label2.Text = "Recv: " + this.counter2.RecvBytes.ToString() + " Send: " + this.counter2.SentBytes.ToString() + " Total: " + this.counter2.TotalBytes.ToString(); } else { label2.Text = ""; } /*this.label1.Text += "."; * if(this.label1.Text.Length > 10)this.label1.Text=".";*/ })); }
void OnServerInitSuccess(NetworkEvent netEvent) { ConnectionIds.Add(new ConnectionId(0)); NodeState = State.Server; m_StartServerCallback.TryInvoke(true); m_StartServerCallback = null; }
private void ProcessNetworkEvent(byte eventcode, object content, int senderid) { Debug.Log("network event: " + eventcode); NetworkEvent recievedNetworkEvent = (NetworkEvent)eventcode; switch (recievedNetworkEvent) { case NetworkEvent.UPDATE_SCORE: if (OnUpdateScore != null) { OnUpdateScore(); } break; case NetworkEvent.TRAP_HIT: if (OnPlayerTrapHit != null) { OnPlayerTrapHit((int)content); } break; case NetworkEvent.TO_SCORING_STATE: GameModel.Instance.ChangeGameState(new ScoringGameState()); break; case NetworkEvent.ROUND_ENDED: if (OnRoundEnded != null) { OnRoundEnded((PhotonPlayer)content); } break; } }
void OnServerInitFailed(NetworkEvent netEvent) { Deinit(); NodeState = State.Uninitialized; m_StartServerCallback.TryInvoke(false); m_StartServerCallback = null; }
/// <summary> /// Calls the corresponding method for each type of received message /// </summary> /// <param name="packet"> The packet that was received</param> /// <param name="handler"> The client handler that called this method</param> private void HandleMessage(Packet packet, ClientHandler handler) { //create a NetworkEvent from the received packet NetworkEvent networkEvent = NetworkEvent.Deserialize(packet.GetDataBytes()); Type type = networkEvent.GetType(); if (type == typeof(HeartBeat)) { RespondToHeartBeat(handler); } else if (type == typeof(InputUpdate)) { RespondToInputUpdate(networkEvent); } else if (type == typeof(ConnectPlayer)) { RespondToConnectPlayer(handler); } else if (type == typeof(DisconnectPlayer)) { RespondToDisconnectPlayer(networkEvent, handler); } else { RespondToUnknownMessage(handler); } }
public void DisplayText(NetworkEvent ne) { this.m_Image = null; DateTime time = new DateTime(ne.timeIndex); this.infoLabel.Text = ""; this.appendText("Sender: " + ne.source); this.appendText("Time: " + time.ToLongDateString() + " " + time.ToLongTimeString()); if (ne is NetworkChunkEvent) { NetworkChunkEvent nce = ne as NetworkChunkEvent; this.appendText("Category: Chunk"); this.appendText("Message Sequence: " + nce.chunk.MessageSequence); this.appendText("Chunk Sequence: " + nce.chunk.ChunkSequence); this.appendText("First Chunk Sequence of Message: " + nce.chunk.FirstChunkSequenceOfMessage); this.appendText("Number of Chunks: " + nce.chunk.NumberOfChunksInMessage); } else if (ne is NetworkMessageEvent) { NetworkMessageEvent nme = ne as NetworkMessageEvent; this.appendText("Category: Message"); this.displayMessageEventRecursive(nme.message); } else if (ne is NetworkNACKMessageEvent) { } else { //Unknown this.infoLabel.Text = "Unknown Type"; } this.doubleBufferPanel.Invalidate(); }
private bool MatchTrigger(IPlatformMessage message, NetworkEvent evt, SensorTrigger info, ref bool textTriggered, ref bool measurementTriggered) { if (!this.VerifySensorTrigger(message, info)) { return(false); } evt.Actions.Add(NetworkEventType.MessageTriggered); if (!textTriggered && info.IsTextTrigger) { textTriggered = true; this.EnqueueToTriggerService(message); } else if (!measurementTriggered && !info.IsTextTrigger) { measurementTriggered = true; this.EnqueueToTriggerService(message); } if (textTriggered && measurementTriggered) { this.m_logger.LogDebug($"Skipping trigger for {message.SensorID}: already queued"); return(true); } return(false); }
public NetworkService() { // Initialize Variable. peer = null; IsConnected = false; eventHandler = new NetworkEvent(); }
public void UpdateDisplay(string _post, char[] _currentWord) { string newText = string.Empty; if (_post == "") { return; } if (_post == new string(_currentWord)) { newText = _post; } else { char[] chars = uI_Text.text.ToCharArray(); char post = _post.ToCharArray()[0]; for (int i = 0; i < chars.Length; i++) { if (_currentWord[i] == post) { chars[i] = post; } } newText = new string(chars); uI_Text.text = newText; } //GameUI._Instance.UpdateUI("word UI", newText); NetworkEvent.UpdateUI("word UI", newText); }
public BaseEvent ProcessEvent(uint data1, uint data2, DateTime time) { NetworkEvent networkEvent = new NetworkEvent(); networkEvent.EventType = (NetworkEventType)(data1 & 0xFF); networkEvent.Flags = (byte)((data1 >> 16) & 0xFF); networkEvent.Time = time; return networkEvent; }
private void HandleIncommingMessage(ref NetworkEvent evt) { MessageDataBuffer buffer = (MessageDataBuffer)evt.MessageData; string msg = Encoding.UTF8.GetString(buffer.Buffer, 0, buffer.ContentLength); //if server -> forward the message to everyone else including the sender if (mIsServer) { //we use the server side connection id to idendify the client string idAndMessage = evt.ConnectionId + ":" + msg; SendString(idAndMessage); Append(idAndMessage); } else { //client received a message from the server -> simply print Append(msg); } //return the buffer so the network can reuse it buffer.Dispose(); }
public string GetEventSenderId(NetworkEvent e) => e.SenderId.ToString();
bool isClientSide(NetworkEvent e) { if (e is SpawnEvent) { SpawnEvent ev = e as SpawnEvent; if (ev.projectile) return true; } return false; }