#DAYU200 thể nghiệm quan # Dayu200 cùng Hi3861 TCP thông tín ( JS ) Nguyên sangTinh hoa
@toc
0. Thuyết minh
OH hệ thống phiên bản: OpenHarmony3.1Release
IDE: 3.0.0.900
Thực hiện ngôn ngữ: JS
1. TCP JS tiếp lời
1.1 tiếp lời phân tích
Tham khảo địa chỉ:Socket liên tiếp
TCP thông tín lưu trình:
Initial TCP ————> Bind IP ————> Connect Target IP ————> Send/Receive
- Khởi động lại IP tương quan phối trí:
- trích dẫn mô khối: import socket from '@ohos.net.socket'
- tăng thêm quyền hạn: ohos.permission.INTERNET, ohos.permission.GET_WIFI_INFO
- sáng tạo đối tượng: let tcp = socket.constructTCPSocketInstance();
- Trói định IP cùng cảng hào
bind(address: NetAddress, callback: AsyncCallback<void>): void
Trói định IP địa chỉ cùng cảng, cảng có thể chỉ định hoặc từ hệ thống tùy cơ phân phối. Sử dụng callback phương pháp làm dị bước phương pháp.
Yêu cầu quyền hạn: ohos.permission.INTERNET
Hệ thống năng lực: SystemCapability.Communication.NetStack
Thí dụ mẫu:
let tcp = socket.constructTCPSocketInstance();
tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
})
- Liên tiếp mục tiêu IP
connect(options: TCPConnectOptions, callback: AsyncCallback<void>): void
Liên tiếp đến chỉ định IP địa chỉ cùng cảng. Sử dụng callback phương pháp làm dị bước phương pháp.
Yêu cầu quyền hạn: ohos.permission.INTERNET
Hệ thống năng lực: SystemCapability.Communication.NetStack
Thí dụ mẫu:
let tcp = socket.constructTCPSocketInstance();
tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1}, timeout: 6000}, err => {
if (err) {
console.log('connect fail');
return;
}
console.log('connect success');
})
- Gửi đi / tiếp thu số liệu
// gửi đi số liệu
send(options: TCPSendOptions, callback: AsyncCallback<void>): void
Thông qua TCPSocket liên tiếp gửi đi số liệu. Sử dụng callback phương thức làm dị bước phương pháp.
Thuyết minh: connect phương pháp thuyên chuyển thành công sau, mới nhưng thuyên chuyển này phương pháp.
Yêu cầu quyền hạn: ohos.permission.INTERNET
Hệ thống năng lực: SystemCapability.Communication.NetStack
Thí dụ mẫu:
tcpSend()
{
tcp.send({
data: this.app_msg,
}, err => {
if (err) {
console.log('send fail');
return;
}
});
},
// tiếp thu số liệu cũng phân tích số liệu vì String
on(type: ‘message’, callback: Callback<{message: ArrayBuffer, remoteInfo: SocketRemoteInfo}>): void
Đặt mua TCPSocket liên tiếp tiếp thu tin tức sự kiện. Sử dụng callback phương thức làm dị bước phương pháp.
Hệ thống năng lực: SystemCapability.Communication.NetStack
tcp.on('message', value => {
console.log( "on message" )
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0;i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log( "on connect received:" + str)
this.receive_data=str;
prompt.showToast({
message:str,
duration:1000
});
});
1.2 TPC send thực hiện
Dựa theo thượng một tiết lưu trình, biên soạn đối ứng JS trình tự là được. UI như sau:
Cái thứ nhất cái nút dùng cho trói định IP, cũng thiết trí đặt mua TCPSocket tương quan đặt mua sự kiện
tcpClient()
{
// đặt mua TCPSocket tương quan đặt mua sự kiện
tcp.on('message', value => {
console.log( "on message" )
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0;i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log( "on connect received:" + str)
this.receive_data=str;
prompt.showToast({
message:str,
duration:1000
});
});
tcp.on('connect', () => {
console.log( "on connect" )
});
tcp.on('close', () => {
console.log( "on close" )
});
// trói định IP địa chỉ cùng cảng.
let bindAddress = {
address: wifi.getIpInfo().ipAddress,
port: 1234,
family: 1
};
tcp.bind(bindAddress, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
prompt.showToast({
message: "bind success",
})
});
},
Cái thứ hai cái nút dùng cho liên tiếp Hi3861:
tcpConnect()
{
prompt.showToast({
message:'wifiAddr'+wifi.isConnected()+wifi.getIpInfo().ipAddress,
});
// let promise = tcp.connect({ address: {address:'192.168.137.92', port: 8888, family: 1}, timeout: 6000});
// promise.then(() => {
// console.log('connect success')
// prompt.showToast({
// message: "connect success",
// });
// }).catch(err => {
// prompt.showToast({
// message: "connect fail",
// });
// console.log('connect fail');
// });
tcp.connect({ address: {address: '192.168.137.92', port: 8888, family: 1}, timeout: 6000}, err => {
if (err) {
console.log('connect fail');
prompt.showToast({
message: "connect fail",
});
return;
}
console.log('connect success');
prompt.showToast({
message: "connect success",
});
})
},
Cái thứ ba cái nút thực hiện gửi đi số liệu:
tcpSend()
{
tcp.send({
data: this.app_msg,
}, err => {
if (err) {
console.log('send fail');
prompt.showToast({
message: "send fail",
});
return;
}
prompt.showToast({
message: "send successful"
})
});
},
2. Hi3861 TCP
2.1 khởi động lại
Tham khảo tiểu hùng phái khai phá bản TCP server trường hợp. Chủ yếu nhiệm vụ là mở ra wifi, thu hoạch chung quanh wifi danh sách.
#define SELECT_WLAN_PORT "wlan0"
int WifiConnect(const char *ssid, const char *psk)
{
WifiScanInfo *info = NULL;
unsigned int size = WIFI_SCAN_HOTSPOT_LIMIT;
static struct netif *g_lwip_netif = NULL;
osDelay(200);
printf( "<--System Init-->\r\n" );
// khởi động lại WIFI
WiFiInit();
// sử có thể WIFI
if (EnableWifi()!= WIFI_SUCCESS)
{
printf( "EnableWifi failed, error = %d\r\n", error);
return -1;
}
// phán đoán WIFI hay không kích hoạt
if (IsWifiActive() == 0)
{
printf( "Wifi station is not actived.\r\n" );
return -1;
}
// phân phối không gian, bảo tồn WiFi tin tức
info = malloc(sizeof(WifiScanInfo) * WIFI_SCAN_HOTSPOT_LIMIT);
if (info == NULL)
{
return -1;
}
// bỏ phiếu tra tìm WiFi danh sách
do{
// trọng trí tiêu chí vị
ssid_count = 0;
g_staScanSuccess = 0;
// bắt đầu rà quét
Scan();
// chờ đợi rà quét kết quả
WaitSacnResult();
// thu hoạch rà quét danh sách
error = GetScanInfoList(info, &size);
}while(g_staScanSuccess!= 1);
// liên tiếp chỉ định WiFi nhiệt điểm
for(uint8_t i = 0; i < ssid_count; i++)
{
if (strcmp(ssid, info[i].ssid) == 0)
{
int result;
printf( "Select:%3d wireless, Waiting...\r\n", i+1);
// copy muốn liên tiếp nhiệt điểm tin tức
WifiDeviceConfig select_ap_config = {0};
strcpy(select_ap_config.ssid, info[i].ssid);
strcpy(select_ap_config.preSharedKey, psk);
select_ap_config.securityType = SELECT_WIFI_SECURITYTYPE;
if (AddDeviceConfig(&select_ap_config, &result) == WIFI_SUCCESS)
{
if (ConnectTo(result) == WIFI_SUCCESS && WaitConnectResult() == 1)
{
printf( "WiFi connect succeed!\r\n" );
g_lwip_netif = netifapi_netif_find(SELECT_WLAN_PORT);
break;
}
}
}
if(i == ssid_count-1)
{
printf( "ERROR: No wifi as expected\r\n" );
while(1) osDelay(100);
}
}
// khởi động DHCP
if (g_lwip_netif)
{
dhcp_start(g_lwip_netif);
printf( "begain to dhcp\r\n" );
}
// chờ đợi DHCP
for(;;)
{
if(dhcp_is_bound(g_lwip_netif) == ERR_OK)
{
printf( "<-- DHCP state:OK -->\r\n" );
// đóng dấu thu hoạch đến IP tin tức
netifapi_netif_common(g_lwip_netif, dhcp_clients_info_show, NULL);
break;
}
printf( "<-- DHCP state:Inprogress -->\r\n" );
osDelay(100);
}
osDelay(100);
return 0;
}
2.2 làm TCP Server
Liên tiếp chỉ định wifi, sáng tạo socket server, nghe lén chỉ định IP cảng.
char *buf = "Hello! I'm BearPi-HM_Nano TCP Server!";
static void TCPServerTask(void)
{
// phục vụ đoan địa chỉ tin tức
struct sockaddr_in server_sock;
// bản cài đặt địa chỉ tin tức
struct sockaddr_in client_sock;
int sin_size;
struct sockaddr_in *cli_addr;
// liên tiếp Wifi
WifiConnect( "r1", "88888889" );
// sáng tạo socket
if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror( "socket is error\r\n" );
exit(1);
}
bzero(&server_sock, sizeof(server_sock));
server_sock.sin_family = AF_INET;
server_sock.sin_addr.s_addr = htonl(INADDR_ANY);
server_sock.sin_port = htons(_PROT_);
// thuyên chuyển bind hàm số trói định socket cùng địa chỉ
if (bind(sock_fd, (struct sockaddr *)&server_sock, sizeof(struct sockaddr)) == -1)
{
perror( "bind is error\r\n" );
exit(1);
}
// thuyên chuyển listen hàm số nghe lén ( chỉ định port nghe lén )
if (listen(sock_fd, TCP_BACKLOG) == -1)
{
perror( "listen is error\r\n" );
exit(1);
}
printf( "start accept\n" );
// thuyên chuyển accept hàm số từ đội ngũ trung
while (1)
{
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sock_fd, (struct sockaddr *)&client_sock, (socklen_t *)&sin_size)) == -1)
{
perror( "accept" );
continue;
}
cli_addr = malloc(sizeof(struct sockaddr));
printf( "accept addr\r\n" );
if (cli_addr!= NULL)
{
memcpy(cli_addr, &client_sock, sizeof(struct sockaddr));
}
// xử lý mục tiêu
ssize_t ret;
while (1)
{
if ((ret = recv(new_fd, recvbuf, sizeof(recvbuf), 0)) == -1)
{
printf( "recv error \r\n" );
}
printf( "recv:%s\r\n", recvbuf);
sleep(2);
if ((ret = send(new_fd, buf, strlen(buf) + 1, 0)) == -1)
{
perror( "send:" );
}
sleep(2);
}
close(new_fd);
}
}
3. Thí nghiệm
Đem Hi3861, Dayu200 đều liên tiếp đến cùng cái wifi hạ, trước đó xứng đôi hảo IP địa chỉ cùng cảng:
Liên tiếp sau Hi3861 chỉ cần tiếp thu đến số liệu liền sẽ phản hồi một đoạn tự phù xuyến, Hi3861 tiếp thu đến số liệu có thể sử dụng xuyến khẩu xem xét:
Phi thường thực dụng biểu thị, học tập