LocalSocket无法正常使用,常见问题:
genLocalAddress(socketFileName: string) {
let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
let sandboxPath: string = context.filesDir + '/' + socketFileName;
let localAddress: socket.LocalAddress = {
address: sandboxPath
};
return localAddress;
} // 创建并绑定本地套接字文件,进行监听。
this.server.listen(this.localAddress).then(() => {
console.info('LocalSocket Server listen success');
}).catch((err: BusinessError) => {
console.error('LocalSocket Server listen fail: ' + JSON.stringify(err));
});
// 订阅LocalSocketServer的connect事件。
this.server.on('connect', (connection: socket.LocalSocketConnection) => {
console.info('LocalSocket Server 监听到客户端连接: ' + JSON.stringify(connection.clientId));
// 订阅LocalSocketConnection相关的事件。
connection.on('message', (value: socket.LocalSocketMessageInfo) => {
console.info('LocalSocket Server total: ' + JSON.stringify(value));
console.info('LocalSocket Server message information: ' + this.decodeMessage(value));
// ...
});
connection.on('error', (err: BusinessError) => {
console.error('LocalSocket Server err:' + JSON.stringify(err));
});
// 向客户端发送数据。
this.sendMessage(connection, 'Hello Client!');
// ...
}); // 启动客户端端前,需要先启动LocalSocketServer,否则报错:2301111 Connection refused
let connectOpt: socket.LocalConnectOptions = {
address: this.localAddress,
timeout: 6000
};
this.client.connect(connectOpt).then(() => {
console.info('LocalSocket Client connect success');
}).catch((err: BusinessError) => {
console.error('LocalSocket Client connect fail: ' + JSON.stringify(err));
});
this.client.on('message', (value: socket.LocalSocketMessageInfo) => {
console.info('LocalSocket Server total: ' + JSON.stringify(value));
console.info('LocalSocket Server message information: ' + this.decodeMessage(value));
});
this.client.on('connect', () => {
console.info('LocalSocket Client on connect');
});
this.client.on('close', () => {
console.info('LocalSocket Client on close');
}); // 正确做法:在on('connect')回调中获取connection对象后再发送消息
this.server.on('connect', (connection: socket.LocalSocketConnection) => {
// 在此处获取到LocalSocketConnection对象后发送消息
this.sendMessage(connection, 'Hello Client!');
});
// 错误做法:在on('connect')回调之外发送消息,此时缺少LocalSocketConnection对象
// this.sendMessage(connection,'Hello Client!'); // connection未定义,消息无法投递 完整示例如下:
import { socket } from '@kit.NetworkKit';
import { common } from '@kit.AbilityKit';
import { util } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct LocalSocketPage {
private server: socket.LocalSocketServer = socket.constructLocalSocketServerInstance();
private client: socket.LocalSocket = socket.constructLocalSocketInstance();
private localAddress: socket.LocalAddress = this.genLocalAddress('socket_1'); // 创建本地文件,server和client均需对此路径具备访问权限
// Start solution1
genLocalAddress(socketFileName: string) {
let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
let sandboxPath: string = context.filesDir + '/' + socketFileName;
let localAddress: socket.LocalAddress = {
address: sandboxPath
};
return localAddress;
}
// End solution1
decodeMessage(data: socket.LocalSocketMessageInfo): string {
if (data?.message) {
let decoder = util.TextDecoder.create('utf-8');
let message = decoder.decodeToString(new Uint8Array(data.message));
return message;
}
return '';
}
sendMessage(socket: socket.LocalSocket | socket.LocalSocketConnection, message: string): void {
let sendOpt: socket.LocalSendOptions = {
data: message
};
socket.send(sendOpt).then(() => {
console.info('LocalSocket send message success');
}).catch((err: BusinessError) => {
console.info('LocalSocket send message failed: ' + JSON.stringify(err));
});
}
build() {
Column({ space: 24 }) {
Button('启动LocalSocket服务端')
.onClick(() => {
// Start solution2
// 创建并绑定本地套接字文件,进行监听。
this.server.listen(this.localAddress).then(() => {
console.info('LocalSocket Server listen success');
}).catch((err: BusinessError) => {
console.error('LocalSocket Server listen fail: ' + JSON.stringify(err));
});
// 订阅LocalSocketServer的connect事件。
this.server.on('connect', (connection: socket.LocalSocketConnection) => {
console.info('LocalSocket Server 监听到客户端连接: ' + JSON.stringify(connection.clientId));
// 订阅LocalSocketConnection相关的事件。
connection.on('message', (value: socket.LocalSocketMessageInfo) => {
console.info('LocalSocket Server total: ' + JSON.stringify(value));
console.info('LocalSocket Server message information: ' + this.decodeMessage(value));
// ...
});
connection.on('error', (err: BusinessError) => {
console.error('LocalSocket Server err:' + JSON.stringify(err));
});
// 向客户端发送数据。
this.sendMessage(connection, 'Hello Client!');
// ...
});
// End solution2
});
Button('启动LocalSocket客户端').onClick(() => {
// Start solution3
// 启动客户端端前,需要先启动LocalSocketServer,否则报错:2301111 Connection refused
let connectOpt: socket.LocalConnectOptions = {
address: this.localAddress,
timeout: 6000
};
this.client.connect(connectOpt).then(() => {
console.info('LocalSocket Client connect success');
}).catch((err: BusinessError) => {
console.error('LocalSocket Client connect fail: ' + JSON.stringify(err));
});
this.client.on('message', (value: socket.LocalSocketMessageInfo) => {
console.info('LocalSocket Server total: ' + JSON.stringify(value));
console.info('LocalSocket Server message information: ' + this.decodeMessage(value));
});
this.client.on('connect', () => {
console.info('LocalSocket Client on connect');
});
this.client.on('close', () => {
console.info('LocalSocket Client on close');
});
// End solution3
});
Button('客户端发送数据').onClick(() => {
// 需要服务端先使用on('connect')、on('message')监听到客户端连接,否则无法监听到消息
this.sendMessage(this.client, 'Hello Server!');
});
}
.height('100%')
.width('100%');
}
}