# 使用MQTT.js库连接CP7

以下示例代码已CP7官方测试支持自动重连，并且稳定性测试。建议使用浏览器领域或小程序开发方向优先使用此库。

使用此例示例代码前请先运行CP7 Core和CP7 WS代理服务，并使用WS代理服务所在IP和端口进行连接测试。

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Coolpy7 mqttjs client demo</title>
    <script src="https://raw.githubusercontent.com/Coolpy7/mqttjs_browser_client_demo/master/lib/browserMqtt.js"></script>
</head>
<script>
    // 连接选项
    const options = {
        connectTimeout: 5000, // 超时时间
        keepalive: 60,
        reconnectPeriod:2000,
        // 认证信息
        clientId: 'cp7-clientid-websocket',
        username: 'cp7-username-websocket',
        password: 'cp7-password-websocket',
    }

    const client = mqtt.connect('mqtt://127.0.0.1:8083', options)

    client.on('connect', function () {
        client.subscribe('coolpy/chatroom', function (err) {
            if (!err) {
                //client.publish('presence', 'Hello mqtt')
                console.log("sub ok")
            }
        })
    })

    client.on('reconnect', (error) => {
        console.log('正在重连:', error)
    })

    client.on('error', (error) => {
        console.log('连接失败:', error)
    })

    client.on('message', function (topic, message) {
        // message is Buffer
        console.log(message.toString())
    })
</script>
<body>

</body>
</html>
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://coolpy7.gitbook.io/coolpy7book/coolpy7-ling-yu-ying-yong-1/shi-yong-mqtt.js-ku-lian-jie-cp7.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
