---
title: "WebSocket.connect"
description: "Opens a ws:// or wss:// connection and creates heartbeat-driven event delivery."
---

```lua
WebSocket.connect(url: string): WebSocketObject
```

---

## Aliases

- `WebSocket.Connect`
- `WebSocket.new`
- `WebSocket.New`
- `websocket.connect`
- `websocket.Connect`
- `websocket.new`
- `websocket.New`

---

## Arguments

<ParamField body="url" type="string" required>
  A ws:// or wss:// endpoint. The server must accept a WebSocket handshake.
</ParamField>

---

## Returns

<ResponseField name="socket" type="WebSocketObject">
  The connected socket facade with Send, Close, OnMessage, and OnClose.
</ResponseField>

Run a local WebSocket server on port 8765 first. Public connect raises on invalid URL/connection/facade failure; use pcall. Hold a strong socket reference. Open waits for the native connection; received messages are pumped on Heartbeat.

**Related types:** [WebSocket types & behavior](/reference/websocket/types).

---

## Example

```lua
local ok, socket = pcall(WebSocket.connect, "ws://127.0.0.1:8765")
if not ok then warn(socket); return end
local messages = socket.OnMessage:Connect(function(data, binary) print(data, binary) end)
local closing = socket.OnClose:Connect(function(reason) print("Closed", reason) end)
local sent, err = socket:Send("hello")
if not sent then warn(err) end
task.delay(5, function()
    socket:Close()
    task.delay(0.2, function() messages:Disconnect(); closing:Disconnect() end)
end)
```
