使用Socket连接时,建议在异步线程或子线程中进行,在UI主线程进行耗时过长影响性能。
// code-linter.json5
{
"rules": {
"@performance/suggest-use-socket-in-async-thread": "warn",
}
} import { socket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Concurrent
async function doSocketTask(address: string, port: number, message: string): Promise<string> {
let tcp = socket.constructTCPSocketInstance();
try {
// 在子线程进行连接
await tcp.connect({ address: { address: address, port: port } });
await tcp.send({ data: message });
return "发送成功并收到响应";
} catch (err) {
let error = err as BusinessError;
throw new Error(`Socket Error: ${error.code} - ${error.message}`);
} finally {
await tcp.close();
}
} import { socket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct SocketBadExample {
@State message: string = '等待发送...';
build() {
Column() {
Text(this.message).fontSize(20).margin(20)
Button('发送数据').onClick(() => {
this.message = '连接中...';
let tcp = socket.constructTCPSocketInstance();
tcp.connect({ address: { address: '192.168.1.100', port: 8080 } })
.then(() => {
this.message = '连接成功';
return tcp.send({ data: 'Hello, HarmonyOS!' });
})
.then(() => {
this.message = '发送完成';
})
.catch((err: BusinessError) => {
this.message = '出错:' + err.message;
});
})
}
.width('100%')
.height('100%')
}
}