You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

connections.md 1.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. ---
  2. uid: Guides.Concepts.ManageConnections
  3. title: Managing Connections
  4. ---
  5. # Managing Connections with Discord.Net
  6. In Discord.Net, once a client has been started, it will automatically
  7. maintain a connection to Discord's gateway until it is manually
  8. stopped.
  9. ## Usage
  10. To start a connection, invoke the `StartAsync` method on a client that
  11. supports a WebSocket connection; to end a connection, invoke the
  12. `StopAsync` method, which gracefully closes any open WebSocket or
  13. UdpSocket connections.
  14. Since the Start/Stop methods only signal to an underlying connection
  15. manager that a connection needs to be started, **they return before a
  16. connection is made.**
  17. As a result, you need to hook into one of the connection-state
  18. based events to have an accurate representation of when a client is
  19. ready for use.
  20. All clients provide a `Connected` and `Disconnected` event, which is
  21. raised respectively when a connection opens or closes. In the case of
  22. the [DiscordSocketClient], this does **not** mean that the client is
  23. ready to be used.
  24. A separate event, `Ready`, is provided on [DiscordSocketClient], which
  25. is raised only when the client has finished guild stream or guild
  26. sync and has a completed guild cache.
  27. [DiscordSocketClient]: xref:Discord.WebSocket.DiscordSocketClient
  28. ### Samples
  29. [!code-csharp[Connection Sample](samples/events.cs)]
  30. ## Reconnection
  31. > [!TIP]
  32. > Avoid running long-running code on the gateway! If you deadlock the
  33. > gateway (as explained in [events]), the connection manager will
  34. > **NOT** be able to recover and reconnect.
  35. Assuming the client disconnected because of a fault on Discord's end,
  36. and not a deadlock on your end, we will always attempt to reconnect
  37. and resume a connection.
  38. Don't worry about trying to maintain your own connections, the
  39. connection manager is designed to be bulletproof and never fail - if
  40. your client does not manage to reconnect, you have found a bug!
  41. [events]: xref:Guides.Concepts.Events