示例代码:
import socket from '@ohos.net.socket';
import wifiManager from '@ohos.wifiManager';
import {resolveIP} from '../common/utils/Utils'
import hilog from '@ohos.hilog';
import connection from '@ohos.net.connection';
let localAddress = resolveIP(wifiManager.getIpInfo().ipAddress);
let localPort = 8085;
@Entry
@Component
struct TestTcpPage {
@State message: string = 'Hello World'
@State recvMessage:string=''
private strInput:string = ""
private TcpSocket:socket.TCPSocket=null
tcpInit(){
this.TcpSocket = socket.constructTCPSocketInstance();
let localAddresspara = {
address:localAddress,
family:1,
port:0
}
this.TcpSocket.bind(localAddresspara)
.then(()=>{
hilog.info(0x0000,'TestTag','connected successfully')
})
.catch(err=>{
hilog.info(0x0000,'TestTag',JSON.stringify(err))
return
})
this.TcpSocket.on('connect',()=>{
this.message = '连接中'
})
this.TcpSocket.on('message',(value)=>{
this.recvMessage = this.resolveArrayBuffer(value.message)
})
}
connectSocket(){
this.TcpSocket.getState()
.then((data)=>{
if(data.isClose)
{
this.tcpInit()
}
let targetAddresspara = {
address:'192.168.100.101',
family:1,
port:8081
};
if(data.isConnected)
{
this.recvMessage = '已经连接成功';
}
else {
this.TcpSocket.connect({address:targetAddresspara})
.then(()=>{
this.recvMessage = '连接成功';
})
.catch(err=>{
this.recvMessage = '连接失败';
})
}
})
.catch(error=>{
this.recvMessage = JSON.stringify(error);
})
}
sendMessage(message: string) {
this.TcpSocket.getState()
.then((data) => {
if (data.isConnected) {
this.TcpSocket.send({ data: message })
.then(() => {
//sucessful
})
.catch(err => {
//send error
})
}
else {
this.connectSocket()
}
})
}
resolveArrayBuffer(message:ArrayBuffer):string{
if(message instanceof ArrayBuffer)
{
let dataView = new DataView(message);
let str="";
for(let i = 0; i<dataView.byteLength; i++)
{
let c = String.fromCharCode(dataView.getUint8(i));
if(c!='\n')
{
str+=c;
}
}
return str;
}
}
aboutToAppear(){
this.tcpInit();
}
build() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold).height('10%')
Row(){
Text('请输入内容:').width('50%')
TextInput().onChange((value:string)=>{
this.strInput = value;
}).width('50%')
}.height('10%')
Row(){
Button('连接')
.onClick((event)=>{
this.connectSocket()
}).width('50%')
Button('发送')
.onClick((event)=>{
this.recvMessage = "发送数据:"+this.strInput;
this.sendMessage(this.strInput)
}).width('50%')
}.height('10%')
Text(){
Span(this.recvMessage)
}
}
.width('100%').height('100%')
}
}
Uitls.ets
export function resolveIP(ip: number): string {
if (ip < 0 || ip > 0xFFFFFFFF) {
throw new Error('The number is not normal!');
}
return (ip >>> 24) + '.' + (ip >> 16 & 0xFF) + '.' + (ip >> 8 & 0xFF) + '.' + (ip & 0xFF);
}