基础库版本3.9.3,开发者工具勾选了不校验合法域名,微信公众平台的服务器域名也配置好了
真机调试也报一样的错误
TCP 错误: {errMsg: "connect fail: invalid port '8089' ", errCode: -4, errno: 1001}
// 存储 TCP Socket 实例
let tcpSocket = null
/**
* 创建 TCP 连接
* @param {Object} options - 连接配置
* @param {string} options.host - 服务器域名(如 'haikongiot.com')
* @param {number} options.port - 服务器端口(如 8089)
* @param {Function} onOpen - 连接成功回调
* @param {Function} onMessage - 接收消息回调(参数:data)
* @param {Function} onError - 错误回调(参数:err)
* @param {Function} onClose - 连接关闭回调
*/
export function createTCPConnection(options) {
const { host, port, onOpen, onMessage, onError, onClose } = options;
console.log(typeof port,port,host)
// 若已有连接,先关闭
if (tcpSocket) {
tcpSocket.close();
tcpSocket = null;
}
// 创建 TCP Socket 实例
tcpSocket = wx.createTCPSocket();
console.log(tcpSocket)
if (!tcpSocket) {
onError?.('创建 TCP 实例失败,可能基础库版本过低(需 ≥2.18.0)');
return;
}
// 监听连接成功
tcpSocket.onConnect(() => {
console.log(`TCP 已连接到 ${host}:${port}`);
onOpen?.(); // 触发外部传入的成功回调
});
// 监听接收消息(数据为 ArrayBuffer 类型)
tcpSocket.onMessage((res) => {
const receivedData = res.data; // ArrayBuffer 格式
// 若需要字符串,可转换:const strData = String.fromCharCode.apply(null, new Uint8Array(receivedData));
console.log('收到 TCP 消息:', receivedData);
onMessage?.(receivedData); // 触发外部消息回调
});
// 监听错误
tcpSocket.onError((err) => {
console.error('TCP 错误:', err);
onError?.(err); // 触发外部错误回调
});
// 监听连接关闭
tcpSocket.onClose((res) => {
console.log('TCP 连接已关闭', res);
onClose?.(); // 触发外部关闭回调
tcpSocket = null; // 清空实例
});
// 发起连接
tcpSocket.connect({
address: host,
port: port
});
}
连接报错TCP 错误: {errMsg: "connect fail: invalid port '8089' ", errCode: -4, errno: 1001}
ip和端口都没问题,在其它socket工具里面可以连接没问题,域名和端口都没问题

没问题了,因为我使用的是8089端口,这个端口在小程序里面是禁止的