工程代码https://download.csdn.net/download/txwtech/89258409?spm=1001.2014.3001.5501
54.HarmonyOS鸿蒙系统 App(ArkTS)tcp socket套接字网络连接收发测试
import socket from '@ohos.net.socket';
import process from '@ohos.process';
import wifiManager from '@ohos.wifiManager';
import common from '@ohos.app.ability.common';
import StringUtils from './uint8array2string';
import StringUtils2 from '../http2/uint8array2string_test'
let tcp = socket.constructTCPSocketInstance();
//let ipAddress = wifiManager.getIpInfo().ipAddress; //真机测试
//let local_ip2 = (ipAddress>>24 &0xFF)+"."+(ipAddress>>16 &0xFF)+"."+(ipAddress>>8 &0xFF)+"."
//+(ipAddress &0xFF) //真机测试
let local_ip2 = '10.0.2.16' //用于模拟器,真机则屏蔽此处
let tcp_on_msg = ''
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
@State local_ip:string = local_ip2
@State local_port:number =6666
@State ip_addr:string ='192.168.10.104'
@State port:number =8080
@State send_msg:string ='send content'
@State recv_msg:string =''
build() {
Column() {
Row(){
Text(' ')
}
Row(){
Text('TCP socket测试连接')
.fontSize(38)
.fontColor(Color.White)
.backgroundColor(Color.Blue)
}
Row(){
Text('本机IP:').fontSize(28)
.backgroundColor(Color.Green)
TextInput({text:`${this.local_ip}`})
.fontSize(28)
.width(280)
.backgroundColor(Color.Transparent)
.onChange((value:string)=>{
this.local_ip = value
})
}
Row(){
Text('端口:').fontSize(28)
.backgroundColor(Color.Green)
TextInput({text:`${this.local_port}`})
.fontSize(28)
.width(280)
.backgroundColor(Color.Transparent)
.onChange((value:string)=>{
this.local_port = parseInt(value, 10); //字符转数字
})
}
Row(){
Text('服务器IP:').fontSize(28)
.backgroundColor(Color.Green)
TextInput({text:`${this.ip_addr}`})
.fontSize(28)
.width(280)
.backgroundColor(Color.Transparent)
.onChange((value:string)=>{
this.ip_addr = value
})
}
Row(){
Text('端口:').fontSize(28)
.backgroundColor(Color.Green)
TextInput({text:`${this.port}`})
.fontSize(28)
.width(280)
.backgroundColor(Color.Transparent)
.onChange((value:string)=>{
this.port = parseInt(value, 10); //字符转数字
})
}
Row(){
Text('发送:').fontSize(28)
}.align(Alignment.Start)
Row(){
TextArea({text:`${this.send_msg}`})
.fontSize(28)
.height(100)
.onChange((value:string)=>{
this.send_msg = value
})
}
Row(){
Text('接收:').fontSize(28)
}.align(Alignment.Start)
Row(){
TextArea({text:`${this.recv_msg}`})
.fontSize(28) //文本自动换行
.height(200)
.onChange((value:string)=>{
this.recv_msg = value
})
}
Row()
{
Button('连接')
.width(100)
.fontSize(28)
.onClick(() => {
// 绑定IP地址和端口。//连接服务器,必须首先绑定本机IP
let bindAddress = {
address: this.local_ip,
port: this.local_port, // 绑定端口,如1234
family: 1
};
tcp.bind(bindAddress, err => {
if (err) {
console.log('bind fail_local');
this.recv_msg = 'connect fail_local,IP:'+this.local_ip
return;
}
console.log('bind success_local');
this.recv_msg = 'connect fail_local,IP:'+this.local_ip
})
let connectAddress = {
address: this.ip_addr,
port: this.port, // 连接端口,如5678
family: 1
};
tcp.connect({
address: connectAddress, timeout: 3000
},err=>{
if (err) {
console.log('connect fail_remote');
this.recv_msg = 'connect fail_remote,IP:'+this.ip_addr
return;
}
console.log('connect success');
this.recv_msg = 'connect success_remote,IP:'+this.ip_addr
}
)
tcp.on('message', value => {
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo)
this.recv_msg = this.recv_msg+StringUtils.arrayBuffer2String(value.message);
});
})
Button('______').onClick((event: ClickEvent) => {
})
Button('发送')
.width(100)
.fontSize(28)
.onClick((event: ClickEvent) => {
tcp.send({
data: this.send_msg
}, err => {
if (err) {
console.log('send fail');
this.recv_msg='send fail_remote'
return;
}
console.log('send success');
this.recv_msg='send success_remote';
})
})
}
Row(){
Button('退出')
.width(100)
.fontSize(28)
.onClick((event: ClickEvent) => {
tcp.close();
const context = getContext(this) as common.UIAbilityContext;
context.terminateSelf();
let applicationContext = context.getApplicationContext();
// applicationContext.killProcessesBySelf().
// then((data)=>
// {console.log('The process running information is:'+ JSON.stringify(data));})
// .catch((error)=>{console.error('error:'+ JSON.stringify(error));})
// process.kill(0, process.pid)
// process.exit(0)
})
}
}
.width('100%')
.padding(20) //边距
.backgroundColor(Color.Gray)
}
}
配置权限:
arkts获取真机本机IP:
连接远程服务器,tcp/ip,必须绑定本机IP
import StringUtils from './uint8array2string';
uint8array2string.ts
import util from '@ohos.util';
class StringUtils {
/**
* string转Uint8Array
* @param value
* @returns
*/
string2Uint8Array1(value: string): Uint8Array {
if (!value) return null;
//
let textEncoder = new util.TextEncoder();
//获取点流并发出 UTF-8 字节流 TextEncoder 的所有实例仅支持 UTF-8 编码
return textEncoder.encodeInto(value)
}
/**
* string转Uint8Array
* @param value 包含要编码的文本的源字符串
* @param dest 存储编码结果的Uint8Array对象实例
* @returns 它返回一个包含读取和写入的两个属性的对象
*/
string2Uint8Array2(value: string, dest: Uint8Array) {
if (!value) return null;
if (!dest) dest = new Uint8Array(value.length);
let textEncoder = new util.TextEncoder();
//read:它是一个数值,指定转换为 UTF-8 的字符串字符数。如果 uint8Array 没有足够的空间,这可能小于 src.length(length of source 字符串)。
//dest:也是一个数值,指定存储在目标 Uint8Array 对象 Array 中的 UTF-8 unicode 的数量。它总是等于阅读。
textEncoder.encodeIntoUint8Array(value, dest)
// let result = textEncoder.encodeIntoUint8Array(value, dest)
// result.read
// result.written
}
/**
* Uint8Array 转 String
* @param input
*/
uint8Array2String(input: Uint8Array) {
let textDecoder = util.TextDecoder.create("utf-8", { ignoreBOM: true })
return textDecoder.decodeWithStream(input, { stream: false });
}
/**
* ArrayBuffer 转 String
* @param input
* @returns
*/
arrayBuffer2String(input: ArrayBuffer) {
return this.uint8Array2String(new Uint8Array(input))
}
}
export default new StringUtils()