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 KiB

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