ChatState









How do I use Chat State
Below are practical examples compiled from projects for learning and reference purposes

Featured Snippets


File name: ChatGui.cs Copy
103     public void OnGUI()
104     {
105         if (!this.IsVisible)
106         {
107             return;
108         }
109
110         GUI.skin.label.wordWrap = true;
111         //GUI.skin.button.richText = true; // this allows toolbar buttons to have bold/colored text. nice to indicate new msgs
112         //GUILayout.Button("lala"); // as richText, html tags could be in text
113
114
115         if (Event.current.type == EventType.KeyDown && (Event.current.keyCode == KeyCode.KeypadEnter || Event.current.keyCode == KeyCode.Return))
116         {
117             if ("ChatInput".Equals(GUI.GetNameOfFocusedControl()))
118             {
119                 // focus on input -> submit it
120                 GuiSendsMsg();
121                 return; // showing the now modified list would result in an error. to avoid this, we just skip this single frame
122             }
123             else
124             {
125                 // assign focus to input
126                 GUI.FocusControl("ChatInput");
127             }
128         }
129
130         GUI.SetNextControlName("");
131         GUILayout.BeginArea(this.GuiRect);
132
133         GUILayout.FlexibleSpace();
134
135         if (this.chatClient.State != ChatState.ConnectedToFrontEnd)
136         {
137             GUILayout.Label("Not in chat yet.");
138         }
139         else
140         {
141             List channels = new List(this.chatClient.PublicChannels.Keys); // this could be cached
142             int countOfPublicChannels = channels.Count;
143             channels.AddRange(this.chatClient.PrivateChannels.Keys);
144
145             if (channels.Count > 0)
146             {
147                 int previouslySelectedChannelIndex = this.selectedChannelIndex;
148                 int channelIndex = channels.IndexOf(this.selectedChannelName);
149                 this.selectedChannelIndex = (channelIndex >= 0) ? channelIndex : 0;
150
151                 this.selectedChannelIndex = GUILayout.Toolbar(this.selectedChannelIndex, channels.ToArray(), GUILayout.ExpandWidth(false));
152                 this.scrollPos = GUILayout.BeginScrollView(this.scrollPos);
153
154                 this.doingPrivateChat = (this.selectedChannelIndex >= countOfPublicChannels);
155                 this.selectedChannelName = channels[this.selectedChannelIndex];
156
157                 if (this.selectedChannelIndex != previouslySelectedChannelIndex)
158                 {
159                     // changed channel -> scroll down, if private: pre-fill "to" field with target user's name
160                     this.scrollPos.y = float.MaxValue;
161                     if (this.doingPrivateChat)
162                     {
163                         string[] pieces = this.selectedChannelName.Split(new char[] {':'}, 3);
164                         this.userIdInput = pieces[1];
165                     }
166                 }
167
168                 GUILayout.Label(ChatGui.WelcomeText);
169
170                 if (this.chatClient.TryGetChannel(selectedChannelName, this.doingPrivateChat, out this.selectedChannel))
171                 {
172                     for (int i = 0; i < this.selectedChannel.Messages.Count; i++)
173                     {
174                         string sender = this.selectedChannel.Senders[i];
175                         object message = this.selectedChannel.Messages[i];
176                         GUILayout.Label(string.Format("{0}: {1}", sender, message));
177                     }
178                 }
179
180                 GUILayout.EndScrollView();
181             }
182         }
183
184
185         GUILayout.BeginHorizontal();
186         if (doingPrivateChat)
187         {
188             GUILayout.Label("to:", GUILayout.ExpandWidth(false));
189             GUI.SetNextControlName("WhisperTo");
190             this.userIdInput = GUILayout.TextField(this.userIdInput, GUILayout.MinWidth(100), GUILayout.ExpandWidth(false));
191             string focussed = GUI.GetNameOfFocusedControl();
192             if (focussed.Equals("WhisperTo"))
193             {
194                 if (this.userIdInput.Equals("username"))
195                 {
196                     this.userIdInput = "";
197                 }
198             }
199             else if (string.IsNullOrEmpty(this.userIdInput))
200             {
201                 this.userIdInput = "username";
202             }
203
204         }
205         GUI.SetNextControlName("ChatInput");
206         inputLine = GUILayout.TextField(inputLine);
207         if (GUILayout.Button("Send", GUILayout.ExpandWidth(false)))
208         {
209             GuiSendsMsg();
210         }
211         GUILayout.EndHorizontal();
212         GUILayout.EndArea();
213     }
File name: ChatGui.cs Copy
311     public void OnChatStateChange(ChatState state)
312     {
313         // use OnConnected() and OnDisconnected()
314         // this method might become more useful in the future, when more complex states are being used.
315     }
File name: ChatClient.cs Copy
51         public ChatState State { get; private set; }
File name: ChatClient.cs Copy
53         public bool CanChat { get { return this.State == ChatState.ConnectedToFrontEnd && this.HasPeer; } }
File name: ChatClient.cs Copy
80         public ChatClient(IChatClientListener listener)
81         {
82             this.listener = listener;
83             this.State = ChatState.Uninitialized;
84
85             this.PublicChannels = new Dictionary();
86             this.PrivateChannels = new Dictionary();
87         }
File name: ChatClient.cs Copy
94         public bool Connect(string address, ConnectionProtocol protocol, string appId, string appVersion, string userId, AuthenticationValues authValues)
95         {
96             if (!this.HasPeer)
97             {
98                 this.chatPeer = new ChatPeer(this, protocol);
99             }
100             else
101             {
102                 this.Disconnect();
103                 if (this.chatPeer.UsedProtocol != protocol)
104                 {
105                     this.chatPeer = new ChatPeer(this, protocol);
106                 }
107             }
108
109#if UNITY
110#pragma warning disable 0162 // the library variant defines if we should use PUN's SocketUdp variant (at all)
111             if (PhotonPeer.NoSocket)
112             {
113#if !UNITY_EDITOR && (UNITY_PS3 || UNITY_ANDROID)
114                 UnityEngine.Debug.Log("Using class SocketUdpNativeDynamic");
115                 this.chatPeer.SocketImplementation = typeof(SocketUdpNativeDynamic);
116#elif !UNITY_EDITOR && UNITY_IPHONE
117                 UnityEngine.Debug.Log("Using class SocketUdpNativeStatic");
118                 this.chatPeer.SocketImplementation = typeof(SocketUdpNativeStatic);
119#elif !UNITY_EDITOR && (UNITY_WINRT)
120                 // this automatically uses a separate assembly-file with Win8-style Socket usage (not possible in Editor)
121#else
122                 Type udpSocket = Type.GetType("ExitGames.Client.Photon.SocketUdp, Assembly-CSharp");
123                 this.chatPeer.SocketImplementation = udpSocket;
124                 if (udpSocket == null)
125                 {
126                     UnityEngine.Debug.Log("ChatClient could not find a suitable C# socket class. The Photon3Unity3D.dll only supports native socket plugins.");
127                 }
128#endif
129                 if (this.chatPeer.SocketImplementation == null)
130                 {
131                     UnityEngine.Debug.Log("No socket implementation set for 'NoSocket' assembly. Please contact Exit Games.");
132                 }
133             }
134#pragma warning restore 0162
135#endif
136
137             this.chatPeer.TimePingInterval = 3000;
138             this.DisconnectedCause = ChatDisconnectCause.None;
139
140             this.CustomAuthenticationValues = authValues;
141             this.UserId = userId;
142             this.AppId = appId;
143             this.AppVersion = appVersion;
144             this.didAuthenticate = false;
145             this.msDeltaForServiceCalls = 100;
146
147
148             // clean all channels
149             this.PublicChannels.Clear();
150             this.PrivateChannels.Clear();
151
152             if (!address.Contains(":"))
153             {
154                 int port = 0;
155                 ProtocolToNameServerPort.TryGetValue(protocol, out port);
156                 address = string.Format("{0}:{1}", address, port);
157             }
158
159             bool isConnecting = this.chatPeer.Connect(address, "NameServer");
160             if (isConnecting)
161             {
162                 this.State = ChatState.ConnectingToNameServer;
163             }
164             return isConnecting;
165         }
File name: ChatClient.cs Copy
620         void IPhotonPeerListener.OnStatusChanged(StatusCode statusCode)
621         {
622             switch (statusCode)
623             {
624                 case StatusCode.Connect:
625                     this.chatPeer.EstablishEncryption();
626                     if (this.State == ChatState.ConnectingToNameServer)
627                     {
628                         this.State = ChatState.ConnectedToNameServer;
629                         this.listener.OnChatStateChange(this.State);
630                     }
631                     else if (this.State == ChatState.ConnectingToFrontEnd)
632                     {
633                         this.AuthenticateOnFrontEnd();
634                     }
635                     break;
636                 case StatusCode.EncryptionEstablished:
637                     // once encryption is availble, the client should send one (secure) authenticate. it includes the AppId (which identifies your app on the Photon Cloud)
638                     if (!this.didAuthenticate)
639                     {
640                         this.didAuthenticate = this.chatPeer.AuthenticateOnNameServer(this.AppId, this.AppVersion, this.chatRegion, this.UserId, this.CustomAuthenticationValues);
641                         if (!this.didAuthenticate)
642                         {
643                             ((IPhotonPeerListener) this).DebugReturn(DebugLevel.ERROR, "Error calling OpAuthenticate! Did not work. Check log output, CustomAuthenticationValues and if you're connected. State: " + this.State);
644                         }
645                     }
646                     break;
647                 case StatusCode.EncryptionFailedToEstablish:
648                     this.State = ChatState.Disconnecting;
649                     this.chatPeer.Disconnect();
650                     break;
651                 case StatusCode.Disconnect:
652                     if (this.State == ChatState.Authenticated)
653                     {
654                         this.ConnectToFrontEnd();
655                     }
656                     else
657                     {
658                         this.State = ChatState.Disconnected;
659                         this.listener.OnChatStateChange(ChatState.Disconnected);
660                         this.listener.OnDisconnected();
661                     }
662                     break;
663             }
664         }
File name: ChatClient.cs Copy
768         private void HandleAuthResponse(OperationResponse operationResponse)
769         {
770             ((IPhotonPeerListener)this).DebugReturn(DebugLevel.INFO, operationResponse.ToStringFull() + " on: " + this.NameServerAddress);
771             if (operationResponse.ReturnCode == 0)
772             {
773                 if (this.State == ChatState.ConnectedToNameServer)
774                 {
775                     this.State = ChatState.Authenticated;
776                     this.listener.OnChatStateChange(this.State);
777
778                     if (operationResponse.Parameters.ContainsKey(ParameterCode.Secret))
779                     {
780                         if (this.CustomAuthenticationValues == null)
781                         {
782                             this.CustomAuthenticationValues = new AuthenticationValues();
783                         }
784                         this.CustomAuthenticationValues.Secret = operationResponse[ParameterCode.Secret] as string;
785                         this.FrontendAddress = (string) operationResponse[ParameterCode.Address];
786
787                         // we disconnect and status handler starts to connect to front end
788                         this.chatPeer.Disconnect();
789                     }
790                     else
791                     {
792                         //TODO: error reaction!
793                     }
794                 }
795                 else if (this.State == ChatState.ConnectingToFrontEnd)
796                 {
797                     this.msDeltaForServiceCalls = this.msDeltaForServiceCalls * 4; // when we arrived on chat server: limit Service calls some more
798
799                     this.State = ChatState.ConnectedToFrontEnd;
800                     this.listener.OnChatStateChange(this.State);
801                     this.listener.OnConnected();
802                 }
803             }
804             else
805             {
806                 //((IPhotonPeerListener)this).DebugReturn(DebugLevel.INFO, operationResponse.ToStringFull() + " NS: " + this.NameServerAddress + " FrontEnd: " + this.frontEndAddress);
807
808                 switch (operationResponse.ReturnCode)
809                 {
810                     case ErrorCode.InvalidAuthentication:
811                         this.DisconnectedCause = ChatDisconnectCause.InvalidAuthentication;
812                         break;
813                     case ErrorCode.CustomAuthenticationFailed:
814                         this.DisconnectedCause = ChatDisconnectCause.CustomAuthenticationFailed;
815                         break;
816                     case ErrorCode.InvalidRegion:
817                         this.DisconnectedCause = ChatDisconnectCause.InvalidRegion;
818                         break;
819                     case ErrorCode.MaxCcuReached:
820                         this.DisconnectedCause = ChatDisconnectCause.MaxCcuReached;
821                         break;
822                     case ErrorCode.OperationNotAllowedInCurrentState:
823                         this.DisconnectedCause = ChatDisconnectCause.OperationNotAllowedInCurrentState;
824                         break;
825                 }
826
827                 this.State = ChatState.Disconnecting;
828                 this.chatPeer.Disconnect();
829             }
830         }
File name: ChatClient.cs Copy
847         private void ConnectToFrontEnd()
848         {
849             this.State = ChatState.ConnectingToFrontEnd;
850
851             this.chatPeer.Connect(this.FrontendAddress, ChatApppName);
852         }

Download file with original file name:ChatState

ChatState 96 lượt xem

Gõ tìm kiếm nhanh...