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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. ---
  2. title: Managing Connections
  3. ---
  4. In Discord.Net, once a client has been started, it will automatically
  5. maintain a connection to Discord's gateway, until it is manually
  6. stopped.
  7. ### Usage
  8. To start a connection, invoke the `StartAsync` method on a client that
  9. supports a WebSocket connection.
  10. These clients include the [DiscordSocketClient] and
  11. [DiscordRpcClient], as well as Audio clients.
  12. To end a connection, invoke the `StopAsync` method. This will
  13. gracefully close any open WebSocket or 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 actually made.**
  17. As a result, you will 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 complete guild cache.
  27. [DiscordSocketClient]: xref:Discord.WebSocket.DiscordSocketClient
  28. [DiscordRpcClient]: xref:Discord.Rpc.DiscordRpcClient
  29. ### Samples
  30. [!code-csharp[Connection Sample](samples/events.cs)]
  31. ### Tips
  32. Avoid running long-running code on the gateway! If you deadlock the
  33. gateway (as explained in [events]), the connection manager will be
  34. unable 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 doesn't manage to reconnect, you've found a bug!
  41. [events]: events.md