> ## Documentation Index
> Fetch the complete documentation index at: https://docs.projectreal.gg/llms.txt
> Use this file to discover all available pages before exploring further.

# WebSocket.connect

> Creates two BindableEvents, opens a WebSocket client WebSocket connection to the provided URL, and yields until the connection attempt finishes. On success, it returns a WebSocket table with OnMessage and OnClose events, Send and Close methods supplied by the methods, and an connection state. Incoming message data is fired with OnMessage as a string. When the receive loop ends, OnClose is fired with no arguments. On connection failure, the function raises an error string that starts with "WebSocket connection failed".

<div className="real-function-page">
  ```lua theme={null}
  WebSocket.connect(url: string): WebSocket
  ```

  ## Aliases

  * `WebSocket.Connect`
  * `websocket.connect`
  * `websocket.Connect`

  ## Arguments

  <ParamField path={"url"} type={"string"} required>
    URL string passed to CURLOPT\_URL before WebSocket client performs the WebSocket connection attempt.
  </ParamField>

  ## Returns

  <ResponseField name={"socket"} type={"WebSocket"}>
    WebSocket table containing OnMessage, OnClose, and connection state. Send and Close are resolved with the WebSocket object methods.
  </ResponseField>

  ## Example

  Open a WebSocket, listen for messages and close events, then use the socket methods.

  ```lua theme={null}
  local socket = WebSocket.connect("wss://example.com/socket")

  socket.OnMessage:Connect(function(message)
      print(message)
  end)

  socket.OnClose:Connect(function()
      print("closed")
  end)

  socket:Send("hello")
  socket:Close()
  ```
</div>
