无长时任务的应用退到后台时,主动断开TCP和UDP连接。
import { UIAbility } from '@kit.AbilityKit';
import { http } from '@kit.NetworkKit';
export default class EntryAbility extends UIAbility {
// ...
onForeground(): void {
// Create an HTTP request based on the service requirements at the foreground
let httpRequest: http.HttpRequest = http.createHttp();
// ...
}
onBackground(): void {
// ...
// Go back to the background and release the http request
httpRequest.destroy();
}
} 有关HTTP数据请求相关接口的使用,详情可以参考使用HTTP访问网络。
import { UIAbility } from '@kit.AbilityKit';
import { socket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
// ...
tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
onForeground(): void {
/**
* In the foreground, create a socket connection and send service data as required, for example:
* this.tcp.bind(ipAddress, (err: BusinessError) => {})
* this.tcp.connect(tcpConnect, (err: BusinessError) => {})
* this.tcp.send(tcpSendOptions, (err: BusinessError) => {})
*/
}
onBackground(): void {
// Go back to the background and close the socket connection
this.tcp.close((err: BusinessError) => {})
}
} 有关网络Socket相关接口的使用,详情可以参考使用Socket访问网络。
import { UIAbility } from '@kit.AbilityKit';
import { webSocket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
// Create a websocket based on service requirements
ws: webSocket.WebSocket = webSocket.createWebSocket();
onForeground(): void {
// Send data through websocket in the foreground
this.ws.on('open', (err: BusinessError, value: Object) => {
console.log("onopen,status:" + JSON.stringify(value));
// When an on ('open') event is received, you can communicate with the server through the send () method
this.ws.send("Hello,server!", (err: BusinessError, value: boolean) => {
if (!err) {
console.log("Message sent successfully");
} else {
console.log("Failed to send the message.Err:" + JSON.stringify(err));
}
});
});
}
onBackground(): void {
// Backstage closes websocket
this.ws.close((err: BusinessError) => {});
}
} 有关网络WebSocket相关接口的使用,详情可以参考使用WebSocket访问网络。