ConnectingToNameServer
How do I use Connecting To Name Server
Below are practical examples compiled from projects for learning and reference purposes
Featured Snippets
File name: NetworkingPeer.cs
Copy
253 public bool Connect(string serverAddress, ServerConnection type)
254 {
255 if (PhotonHandler.AppQuits)
256 {
257 Debug.LogWarning("Ignoring Connect() because app gets closed. If this is an error, check PhotonHandler.AppQuits.");
258 return false;
259 }
260
261 if (PhotonNetwork.connectionStateDetailed == global::PeerState.Disconnecting)
262 {
263 Debug.LogError("Connect() failed. Can't connect while disconnecting (still). Current state: " + PhotonNetwork.connectionStateDetailed);
264 return false;
265 }
266
267 // connect might fail, if the DNS name can't be resolved or if no network connection is available
268 bool connecting = base.Connect(serverAddress, "");
269 if (connecting)
270 {
271 switch (type)
272 {
273 case ServerConnection.NameServer:
274 State = global::PeerState.ConnectingToNameServer;
275 break;
276 case ServerConnection.MasterServer:
277 State = global::PeerState.ConnectingToMasterserver;
278 break;
279 case ServerConnection.GameServer:
280 State = global::PeerState.ConnectingToGameserver;
281 break;
282 }
283 }
284
285 return connecting;
286 }
File name: NetworkingPeer.cs
Copy
294 public bool ConnectToNameServer()
295 {
296 if (PhotonHandler.AppQuits)
297 {
298 Debug.LogWarning("Ignoring Connect() because app gets closed. If this is an error, check PhotonHandler.AppQuits.");
299 return false;
300 }
301
302 IsUsingNameServer = true;
303 this.CloudRegion = CloudRegionCode.none;
304
305 if (this.State == global::PeerState.ConnectedToNameServer)
306 {
307 return true;
308 }
309
310 #if RHTTP
311 string address = (this.UsedProtocol == ConnectionProtocol.RHttp) ? this.NameServerAddressHttp : this.NameServerAddress;
312 #else
313 string address = this.NameServerAddress;
314 #endif
315
316 if (!address.Contains(":"))
317 {
318 int port = 0;
319 ProtocolToNameServerPort.TryGetValue(this.UsedProtocol, out port);
320 address = string.Format("{0}:{1}", address, port);
321 Debug.Log("Server to connect to: " + address + " settings protocol: " + PhotonNetwork.PhotonServerSettings.Protocol);
322 }
323 if (!base.Connect(address, "ns"))
324 {
325 return false;
326 }
327
328 this.State = global::PeerState.ConnectingToNameServer;
329 return true;
330 }
File name: NetworkingPeer.cs
Copy
336 public bool ConnectToRegionMaster(CloudRegionCode region)
337 {
338 if (PhotonHandler.AppQuits)
339 {
340 Debug.LogWarning("Ignoring Connect() because app gets closed. If this is an error, check PhotonHandler.AppQuits.");
341 return false;
342 }
343
344 IsUsingNameServer = true;
345 this.CloudRegion = region;
346
347 if (this.State == global::PeerState.ConnectedToNameServer)
348 {
349 return this.OpAuthenticate(this.mAppId, this.mAppVersionPun, this.PlayerName, this.CustomAuthenticationValues, region.ToString());
350 }
351
352 #if RHTTP
353 string address = (this.UsedProtocol == ConnectionProtocol.RHttp) ? this.NameServerAddressHttp : this.NameServerAddress;
354 #else
355 string address = this.NameServerAddress;
356 #endif
357
358 if (!address.Contains(":"))
359 {
360 int port = 0;
361 ProtocolToNameServerPort.TryGetValue(this.UsedProtocol, out port);
362 address = string.Format("{0}:{1}", address, port);
363 //Debug.Log("Server to connect to: "+ address + " settings protocol: " + PhotonNetwork.PhotonServerSettings.Protocol);
364 }
365 if (!base.Connect(address, "ns"))
366 {
367 return false;
368 }
369
370 this.State = global::PeerState.ConnectingToNameServer;
371 return true;
372 }
File name: NetworkingPeer.cs
Copy
1411 public void OnStatusChanged(StatusCode statusCode)
1412 {
1413 if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1414 Debug.Log(string.Format("OnStatusChanged: {0}", statusCode.ToString()));
1415
1416 switch (statusCode)
1417 {
1418 case StatusCode.Connect:
1419 if (this.State == global::PeerState.ConnectingToNameServer)
1420 {
1421 if (PhotonNetwork.logLevel >= PhotonLogLevel.Full)
1422 Debug.Log("Connected to NameServer.");
1423
1424 this.server = ServerConnection.NameServer;
1425 if (this.CustomAuthenticationValues != null)
1426 {
1427 this.CustomAuthenticationValues.Secret = null; // when connecting to NameServer, invalidate any auth values
1428 }
1429 }
1430
1431 if (this.State == global::PeerState.ConnectingToGameserver)
1432 {
1433 if (PhotonNetwork.logLevel >= PhotonLogLevel.Full)
1434 Debug.Log("Connected to gameserver.");
1435
1436 this.server = ServerConnection.GameServer;
1437 this.State = global::PeerState.ConnectedToGameserver;
1438 }
1439
1440 if (this.State == global::PeerState.ConnectingToMasterserver)
1441 {
1442 if (PhotonNetwork.logLevel >= PhotonLogLevel.Full)
1443 Debug.Log("Connected to masterserver.");
1444
1445 this.server = ServerConnection.MasterServer;
1446 this.State = global::PeerState.ConnectedToMaster;
1447
1448 if (this.IsInitialConnect)
1449 {
1450 this.IsInitialConnect = false; // after handling potential initial-connect issues with special messages, we are now sure we can reach a server
1451 SendMonoMessage(PhotonNetworkingMessage.OnConnectedToPhoton);
1452 }
1453 }
1454
1455 this.EstablishEncryption(); // always enable encryption
1456
1457 if (this.IsAuthorizeSecretAvailable)
1458 {
1459 // if we have a token we don't have to wait for encryption (it is encrypted anyways, so encryption is just optional later on)
1460 this.didAuthenticate = this.OpAuthenticate(this.mAppId, this.mAppVersionPun, this.PlayerName, this.CustomAuthenticationValues, this.CloudRegion.ToString());
1461 if (this.didAuthenticate)
1462 {
1463 this.State = global::PeerState.Authenticating;
1464 }
1465 }
1466 break;
1467
1468 case StatusCode.EncryptionEstablished:
1469 // on nameserver, the "process" is stopped here, so the developer/game can either get regions or authenticate with a specific region
1470 if (this.server == ServerConnection.NameServer)
1471 {
1472 this.State = global::PeerState.ConnectedToNameServer;
1473
1474 if (!this.didAuthenticate && this.CloudRegion == CloudRegionCode.none)
1475 {
1476 // this client is not setup to connect to a default region. find out which regions there are!
1477 this.OpGetRegions(this.mAppId);
1478 }
1479 }
1480
1481 // we might need to authenticate automatically now, so the client can do anything at all
1482 if (!this.didAuthenticate && (!this.IsUsingNameServer || this.CloudRegion != CloudRegionCode.none))
1483 {
1484 // once encryption is availble, the client should send one (secure) authenticate. it includes the AppId (which identifies your app on the Photon Cloud)
1485 this.didAuthenticate = this.OpAuthenticate(this.mAppId, this.mAppVersionPun, this.PlayerName, this.CustomAuthenticationValues, this.CloudRegion.ToString());
1486 if (this.didAuthenticate)
1487 {
1488 this.State = global::PeerState.Authenticating;
1489 }
1490 }
1491 break;
1492
1493 case StatusCode.EncryptionFailedToEstablish:
1494 Debug.LogError("Encryption wasn't established: " + statusCode + ". Going to authenticate anyways.");
1495 this.OpAuthenticate(this.mAppId, this.mAppVersionPun, this.PlayerName, this.CustomAuthenticationValues, this.CloudRegion.ToString()); // TODO: check if there are alternatives
1496 break;
1497
1498 case StatusCode.Disconnect:
1499 this.didAuthenticate = false;
1500 this.isFetchingFriends = false;
1501 if (server == ServerConnection.GameServer) this.LeftRoomCleanup();
1502 if (server == ServerConnection.MasterServer) this.LeftLobbyCleanup();
1503
1504 if (this.State == global::PeerState.DisconnectingFromMasterserver)
1505 {
1506 if (this.Connect(this.mGameserver, ServerConnection.GameServer))
1507 {
1508 this.State = global::PeerState.ConnectingToGameserver;
1509 }
1510 }
1511 else if (this.State == global::PeerState.DisconnectingFromGameserver || this.State == global::PeerState.DisconnectingFromNameServer)
1512 {
1513 if (this.Connect(this.MasterServerAddress, ServerConnection.MasterServer))
1514 {
1515 this.State = global::PeerState.ConnectingToMasterserver;
1516 }
1517 }
1518 else
1519 {
1520 if (this.CustomAuthenticationValues != null)
1521 {
1522 this.CustomAuthenticationValues.Secret = null; // invalidate any custom auth secrets
1523 }
1524
1525 this.State = global::PeerState.PeerCreated; // if we set another state here, we could keep clients from connecting in OnDisconnectedFromPhoton right here.
1526 SendMonoMessage(PhotonNetworkingMessage.OnDisconnectedFromPhoton);
1527 }
1528 break;
1529
1530 case StatusCode.SecurityExceptionOnConnect:
1531 case StatusCode.ExceptionOnConnect:
1532 this.State = global::PeerState.PeerCreated;
1533 if (this.CustomAuthenticationValues != null)
1534 {
1535 this.CustomAuthenticationValues.Secret = null; // invalidate any custom auth secrets
1536 }
1537
1538 DisconnectCause cause = (DisconnectCause)statusCode;
1539 SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, cause);
1540 break;
1541
1542 case StatusCode.Exception:
1543 if (this.IsInitialConnect)
1544 {
1545 Debug.LogError("Exception while connecting to: " + this.ServerAddress + ". Check if the server is available.");
1546 if (this.ServerAddress == null || this.ServerAddress.StartsWith("127.0.0.1"))
1547 {
1548 Debug.LogWarning("The server address is 127.0.0.1 (localhost): Make sure the server is running on this machine. Android and iOS emulators have their own localhost.");
1549 if (this.ServerAddress == this.mGameserver)
1550 {
1551 Debug.LogWarning("This might be a misconfiguration in the game server config. You need to edit it to a (public) address.");
1552 }
1553 }
1554
1555 this.State = global::PeerState.PeerCreated;
1556 cause = (DisconnectCause)statusCode;
1557 SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, cause);
1558 }
1559 else
1560 {
1561 this.State = global::PeerState.PeerCreated;
1562
1563 cause = (DisconnectCause)statusCode;
1564 SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, cause);
1565 }
1566
1567 this.Disconnect();
1568 break;
1569
1570 case StatusCode.TimeoutDisconnect:
1571 case StatusCode.ExceptionOnReceive:
1572 case StatusCode.DisconnectByServer:
1573 case StatusCode.DisconnectByServerLogic:
1574 case StatusCode.DisconnectByServerUserLimit:
1575 if (this.IsInitialConnect)
1576 {
1577 Debug.LogWarning(statusCode + " while connecting to: " + this.ServerAddress + ". Check if the server is available.");
1578
1579 cause = (DisconnectCause)statusCode;
1580 SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, cause);
1581 }
1582 else
1583 {
1584 cause = (DisconnectCause)statusCode;
1585 SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, cause);
1586 }
1587 if (this.CustomAuthenticationValues != null)
1588 {
1589 this.CustomAuthenticationValues.Secret = null; // invalidate any custom auth secrets
1590 }
1591
1592 this.Disconnect();
1593 break;
1594
1595 case StatusCode.SendError:
1596 // this.mListener.clientErrorReturn(statusCode);
1597 break;
1598
1599 case StatusCode.QueueOutgoingReliableWarning:
1600 case StatusCode.QueueOutgoingUnreliableWarning:
1601 case StatusCode.QueueOutgoingAcksWarning:
1602 case StatusCode.QueueSentWarning:
1603 // this.mListener.warningReturn(statusCode);
1604 break;
1605
1606 case StatusCode.QueueIncomingReliableWarning:
1607 case StatusCode.QueueIncomingUnreliableWarning:
1608 Debug.Log(statusCode + ". This client buffers many incoming messages. This is OK temporarily. With lots of these warnings, check if you send too much or execute messages too slow. " + (PhotonNetwork.isMessageQueueRunning? "":"Your isMessageQueueRunning is false. This can cause the issue temporarily.") );
1609 break;
1610
1611 // // TCP "routing" is an option of Photon that's not currently needed (or supported) by PUN
1612 //case StatusCode.TcpRouterResponseOk:
1613 // break;
1614 //case StatusCode.TcpRouterResponseEndpointUnknown:
1615 //case StatusCode.TcpRouterResponseNodeIdUnknown:
1616 //case StatusCode.TcpRouterResponseNodeNotReady:
1617
1618 // this.DebugReturn(DebugLevel.ERROR, "Unexpected router response: " + statusCode);
1619 // break;
1620
1621 default:
1622
1623 // this.mListener.serverErrorReturn(statusCode.value());
1624 Debug.LogError("Received unknown status code: " + statusCode);
1625 break;
1626 }
1627
1628 this.externalListener.OnStatusChanged(statusCode);
1629 }
File name: PhotonHandler.cs
Copy
232 internal IEnumerator PingAvailableRegionsCoroutine(bool connectToBest)
233 {
234 BestRegionCodeCurrently = CloudRegionCode.none;
235 while (PhotonNetwork.networkingPeer.AvailableRegions == null)
236 {
237 if (PhotonNetwork.connectionStateDetailed != PeerState.ConnectingToNameServer && PhotonNetwork.connectionStateDetailed != PeerState.ConnectedToNameServer)
238 {
239 Debug.LogError("Call ConnectToNameServer to ping available regions.");
240 yield break; // break if we don't connect to the nameserver at all
241 }
242
243 Debug.Log("Waiting for AvailableRegions. State: " + PhotonNetwork.connectionStateDetailed + " Server: " + PhotonNetwork.Server + " PhotonNetwork.networkingPeer.AvailableRegions " + (PhotonNetwork.networkingPeer.AvailableRegions != null));
244 yield return new WaitForSeconds(0.25f); // wait until pinging finished (offline mode won't ping)
245 }
246
247 if (PhotonNetwork.networkingPeer.AvailableRegions == null || PhotonNetwork.networkingPeer.AvailableRegions.Count == 0)
248 {
249 Debug.LogError("No regions available. Are you sure your appid is valid and setup?");
250 yield break; // break if we don't get regions at all
251 }
252
253 //#if !UNITY_EDITOR && (UNITY_ANDROID || UNITY_IPHONE)
254 //#pragma warning disable 0162 // the library variant defines if we should use PUN's SocketUdp variant (at all)
255 //if (PhotonPeer.NoSocket)
256 //{
257 // if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
258 // {
259 // Debug.Log("PUN disconnects to re-use native sockets for pining servers and to find the best.");
260 // }
261 // PhotonNetwork.Disconnect();
262 //}
263 //#pragma warning restore 0162
264 //#endif
265
266 PhotonPingManager pingManager = new PhotonPingManager();
267 foreach (Region region in PhotonNetwork.networkingPeer.AvailableRegions)
268 {
269 SP.StartCoroutine(pingManager.PingSocket(region));
270 }
271
272 while (!pingManager.Done)
273 {
274 yield return new WaitForSeconds(0.1f); // wait until pinging finished (offline mode won't ping)
275 }
276
277
278 Region best = pingManager.BestRegion;
279 PhotonHandler.BestRegionCodeCurrently = best.Code;
280 PhotonHandler.BestRegionCodeInPreferences = best.Code;
281
282 Debug.Log("Found best region: " + best.Code + " ping: " + best.Ping + ". Calling ConnectToRegionMaster() is: " + connectToBest);
283
284
285 if (connectToBest)
286 {
287 PhotonNetwork.networkingPeer.ConnectToRegionMaster(best.Code);
288 }
289 }
File name: PhotonNetwork.cs
Copy
84 {
85 get
86 {
87 if (offlineMode)
88 {
89 return true;
90 }
91
92 if (networkingPeer == null)
93 {
94 return false;
95 }
96
97 return !networkingPeer.IsInitialConnect && networkingPeer.State != PeerState.PeerCreated && networkingPeer.State != PeerState.Disconnected && networkingPeer.State != PeerState.Disconnecting && networkingPeer.State != PeerState.ConnectingToNameServer;
98 }
99 }
File name: PhotonNetwork.cs
Copy
113 {
114 get
115 {
116 // connected property will check offlineMode and networkingPeer being null
117 if (!connected)
118 {
119 return false;
120 }
121
122 if (offlineMode)
123 {
124 return true;
125 }
126
127 switch (connectionStateDetailed)
128 {
129 case PeerState.PeerCreated:
130 case PeerState.Disconnected:
131 case PeerState.Disconnecting:
132 case PeerState.Authenticating:
133 case PeerState.ConnectingToGameserver:
134 case PeerState.ConnectingToMasterserver:
135 case PeerState.ConnectingToNameServer:
136 case PeerState.Joining:
137 case PeerState.Leaving:
138 return false; // we are not ready to execute any operations
139 }
140
141 return true;
142 }
143 }
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 }
ConnectingToNameServer 111 lượt xem
Gõ tìm kiếm nhanh...