Browse Source

after test

module-tcpserver-mqtt-t4j-faceSDK
zmt 3 years ago
parent
commit
96d8c62bb3
  1. 32
      uniappWWW/unipluginDemo/pages/sample/ext-module-vue.vue
  2. 224
      uniappWWW/unipluginDemo/utils/8inFileOperate.js
  3. 391
      uniappWWW/unipluginDemo/utils/download.js
  4. 25
      zmt_module/src/main/java/io/dcloud/zmt_module/tcpServer/SocketHelper.java
  5. 22
      zmt_module/src/main/java/io/dcloud/zmt_module/tcpServer/TCPTask.java
  6. 204
      zmt_module/src/main/java/io/dcloud/zmt_module/tcpServer/TcpServer.java
  7. 64
      zmt_module/src/main/java/io/dcloud/zmt_module/zmtClass.java

32
uniappWWW/unipluginDemo/pages/sample/ext-module-vue.vue

@ -1,6 +1,8 @@
<template>
<div class="content">
<button class="btn" type="primary" @click="getFileList">getFileList</button>
<button class="btn" type="primary" @click="deleteAndroidFaceImage">deleteAndroidFaceImage</button>
<button class="btn" type="primary" @click="gotoNativePage">跳转原生Activity</button>
<button class="btn" type="primary" @click="initTcp">[开启TcpServer]</button>
<button class="btn" type="primary" @click="closeTcp">[关闭TcpServer]</button>
@ -38,6 +40,7 @@
// #endif
import {timeFormat} from "../../utils/timeFormat.js"
import FileOperate from '../../utils/8inFileOperate.js';
export default {
onLoad() {
@ -54,7 +57,32 @@
}
},
methods: {
async getFileList(){
let name = "33信息2"
let res = await FileOperate.getFileChildrenList("Face-Sync")
console.log(res,"000")
res.map((item)=>{
if(item.split(".")[0]==name) {
this.log("命中后删除")
this.deleteAndroidFaceImage(item)
}
return item
})
// res.map((item)=>{
// if(item.split(".")[0]==name) {
// this.log("")
// this.deleteAndroidFaceImage(item)
// }
// })
},
async deleteAndroidFaceImage(name){
let res = await FileOperate.deleteAndroidFaceImage(name)
this.log(res)
console.log(77777,res)
},
initAPPListener(){
// #ifdef APP-PLUS
let that = this

224
uniappWWW/unipluginDemo/utils/8inFileOperate.js

@ -0,0 +1,224 @@
import downloadImg from "./download.js"
/*
fileName: 需要查询的目录名
*/
async function getFileChildrenList(fileName){
let fs = await downloadImg.requestFileSystem(plus.io.PUBLIC_DOWNLOADS); //获取所要操作根目录File System
let faceSyncEntry = await downloadImg.getDirectory({
//在PUBLIC_DOWNLOADS下定义人脸库同步文件夹"Face-Sync" Success-Import
OriginPathEntry: fs.root,
newFileName: fileName
});
return downloadImg.getFileChildrenList(faceSyncEntry).then((res)=>{
return res
}).catch((e)=>{
console.log("获取文件列表失败:",e)
})
}
/*
fileName: 需要删除的文件名
*/
async function deleteAndroidFaceImage(fileName){
let item = {
"deleteFile" : true,
"name": fileName
}
let fs = await downloadImg.requestFileSystem(plus.io.PUBLIC_DOWNLOADS); //获取所要操作根目录File System
let url = item.url; //测试url---------
let newName = item.name;
let faceSyncEntry = await downloadImg.getDirectory({
//在PUBLIC_DOWNLOADS下定义人脸库同步文件夹"Face-Sync" Success-Import
OriginPathEntry: fs.root,
newFileName: 'Face-Sync'
});
let newNameFileEntry = await downloadImg.resolveLocalFileSystemURL(faceSyncEntry.fullPath + newName).catch(e => {
console.log('目标文件可以操作', e);
});
if (newNameFileEntry) {
console.log('存在缓存的同名文件:', newNameFileEntry.fullPath);
if(item.deleteFile){
let delResult = await downloadImg.removeFile(newNameFileEntry); //删除已存在的文件
console.log("删除同名文件结果:",delResult)
return delResult
}
if(item.forceDownload){//当本地存在缓存时,是否强制删除后重新下载
let delResult = await downloadImg.removeFile(newNameFileEntry); //删除已存在的文件
}else{
return newNameFileEntry.fullPath //返回已缓存文件路径
}
}else{
console.log("不存在同名文件:"+fileName)
}
}
/*
直接处理接口数据,下载列表并返回下载结果
并同时处理request_time,检测确保当完成列表下载后,本地再存储request_time
*/
async function downloadFileList(res){
// await asyncSetTimeOut(3000) //延时,手动断网,模拟下载失败
return new Promise(async(rs,rj)=>{
let {list,request_time,total} = res
console.log(request_time,total);
let downloadSuccessList = []
for (var i=0; i < list.length; i++) {
try{
await checkNetworkUsable()
console.log("当前第"+(i+1)+"张, 总需下载:"+(list.length))
let local_path = await downloadFileImg(list[i])
downloadSuccessList.push(local_path);
list[i]['local_path'] = local_path
}catch(e){
//TODO handle the exception
// util.showNone(e)
console.error("下载失败:",e);
list[i]['error'] = e
continue
}
}
res.list = list
checkRequestTime(res)
rs(list)
})
}
/*,,
*/
function checkRequestTime(res){
if(res.list.every(e=>e.local_path)){
setRequestTime(res)
}
}
/*downloadFileList ,pluginuser_idstring
: 15,17
*/
function getDataForPlugin(list){
return list.map(e=>{
if(e.local_path)return e.user_id
}).join(",")
}
/*
*/
function checkNetworkUsable(){
return new Promise((rs,rj)=>{
uni.getNetworkType({
success: function (res) {
console.log("checkNetworkUsable 当前可用网络:",res.networkType);
rs(true)
},
fail: function (err) {
console.log(err);
rj(false)
}
});
})
}
/*
后台约定,人脸更新机制为带时间请求
*/
function setRequestTime(res){
if(res.request_time){
uni.setStorageSync("request_time",res.request_time)
}
}
/*
*/
function getRequestTime(){
return new Promise((rs,rj)=>{
let _time = ""
try{
_time = uni.getStorageSync("request_time")
}catch(e){
console.warn("请求时间戳异常:",e);
}
rs(_time)
})
}
async function asyncSetTimeOut(time){
const res = await new Promise(resolve => {
setTimeout(() => resolve("asyncSetTimeOut"), time||1000);
});
return res
}
/*
//下载文件,转存后,按user_id重命名,并返回最终文件本地路径.
//当有重复文件时,覆盖
item:{
pic_url:"",user_id:"",update_time:""
}
*/
async function downloadFileImg(item) {
let fs = await downloadImg.requestFileSystem(plus.io.PUBLIC_DOWNLOADS); //获取所要操作根目录File System
let url = item.pic_url; //测试url---------
let onProgresCallBack = function(e) {
//预留下载进度封装拓展
console.log('下载中...user_id:'+item.user_id, e);
};
let tempDownloadFilePath = await downloadImg.getDownloadFile({
url,
onProgresCallBack
}); //获取下载文件临时路径
let savedFilePath = await downloadImg.getSaveFile(tempDownloadFilePath); //将文件临时路径长久存储并清除
let newName = item.user_id + '.' + (savedFilePath.split('.')[1] ||
'jpg'); //命名与android约定的文件名: [user_id].jpg------------
newName = item.user_id + getName(url);
// console.log(tempDownloadFilePath, savedFilePath.split('.')[1], savedFilePath);
let savedFilePathEntry = await downloadImg.resolveLocalFileSystemURL(savedFilePath); //获取下载后存储的文件Entry
let faceSyncEntry = await downloadImg.getDirectory({
//在PUBLIC_DOWNLOADS下定义人脸库同步文件夹"Face-Sync"
OriginPathEntry: fs.root,
newFileName: 'Face-Sync'
});
let newNameFileEntry = await downloadImg.resolveLocalFileSystemURL(faceSyncEntry.fullPath + newName).catch(
e => {
console.log('目标文件可以操作', e);
});
if (newNameFileEntry) {
console.log('删除存在的同名文件:', newNameFileEntry.fullPath);
let delResult = await downloadImg.removeFile(newNameFileEntry); //删除已存在的文件
}
let reNamePathEntry = await downloadImg.moveFileTo(savedFilePathEntry, faceSyncEntry, newName); //重命名文件到人脸库同步文件夹
// console.log(savedFilePath,newName,reNamePathEntry.fullPath)
return reNamePathEntry.fullPath;
}
function getName(url) {
let end = '.';
let urlarr = url.split('.');
let endname = urlarr[urlarr.length];
if (endname != 'jpg' || endname != 'png' || endname != 'jpeg' || endname != 'PNG' || endname != 'JPG' || endname != 'JPEG') endname = 'jpg';
return (end += endname);
}
//递归清空本地同步文件目录及子目录
async function clearDownloadFace(fileName){
let fs = await downloadImg.requestFileSystem(plus.io.PUBLIC_DOWNLOADS); //获取所要操作根目录File System
let faceSyncEntry = await downloadImg.getDirectory({
//在PUBLIC_DOWNLOADS下定义人脸库同步文件夹[fileName]
OriginPathEntry: fs.root,
newFileName: fileName
});
let newNameFileEntry = await downloadImg.resolveLocalFileSystemURL(faceSyncEntry.fullPath).catch(
e => {
console.log('操作目标文件', e);
});
await downloadImg.removeFileAll(newNameFileEntry).then(e=>{
console.log(fileName,"删除:",e);
})
}
module.exports = {
downloadFileImg,
clearDownloadFace,
downloadFileList,
getRequestTime,
getDataForPlugin,
asyncSetTimeOut,
deleteAndroidFaceImage,
getFileChildrenList
}

391
uniappWWW/unipluginDemo/utils/download.js

@ -0,0 +1,391 @@
let downloadTask;
async function readLocal(){
let fs = await requestFileSystem(plus.io.PUBLIC_DOWNLOADS); //获取所要操作根目录File System
let mFileEntry = await getDirectory({
OriginPathEntry: fs.root,
newFileName: 'OXSyncConfig'
});
let mConfigEntry = await mGetFile(mFileEntry,"config.json")
let mReadResult = await mFile(mConfigEntry)
console.log("读取结果:",mReadResult);
return mReadResult
}
async function writeLocal(msg){
let fs = await requestFileSystem(plus.io.PUBLIC_DOWNLOADS); //获取所要操作根目录File System
let mFileEntry = await getDirectory({
OriginPathEntry: fs.root,
newFileName: 'OXSyncConfig'
});
let mConfigEntry = await mGetFile(mFileEntry,"config.json")
// console.log(mConfigEntry.fullPath);
let mWriteResult = await mCreateWriter(mConfigEntry,msg)
console.log("写入结果:",mWriteResult);
return mWriteResult
}
async function writeLocalOld(msg){
//存储信息到本地,如没有文件,则创建, 有则读取存入
let fs = await requestFileSystem(plus.io.PUBLIC_DOWNLOADS); //获取所要操作根目录File System
let mFileEntry = await getDirectory({
//在PUBLIC_DOWNLOADS下定义人脸库同步文件夹"Face-Sync"
OriginPathEntry: fs.root,
newFileName: 'OXSyncConfig'
});
// let newNameFileEntry = await resolveLocalFileSystemURL(mFileEntry.fullPath + newName).catch(e => {
// console.log('目标文件可以操作', e);
// });
let savedFilePathEntry = await resolveLocalFileSystemURL(mFileEntry.fullPath + "config.json"); //获取下载后存储的文件Entry
let write_result = writeFile(mFileEntry,"config.json",msg)
console.log(9999,JSON.stringify(write_result))
}
async function readLocalOld(){
// 读取本地文件
console.log("readLocal begin")
let newName = "oxconfig.txt"
let fs = await requestFileSystem(plus.io.PUBLIC_DOWNLOADS); //获取所要操作根目录File System
let mFileEntry = await getDirectory({
//在PUBLIC_DOWNLOADS下定义人脸库同步文件夹"Face-Sync"
OriginPathEntry: fs.root,
newFileName: 'OXSyncConfig'
});
let newNameFileEntry = await resolveLocalFileSystemURL(mFileEntry.fullPath + newName).catch(e => {
console.log('目标文件可以操作', e);
});
if (newNameFileEntry) {
console.log("配置文件已存在准:",newNameFileEntry.fullPath)
// return newNameFileEntry.fullPath //返回已缓存文件路径
}
// mFileEntry是操作对象DirectoryEntry
let result = getFile(mFileEntry,"config.json")
console.log("result: "+JSON.stringify(result))
}
//下载数据,当有缓存时直接使用
//item.url 下载地址
//item.name 文件名
//item.forceDownload 当本地存在缓存时,是否强制删除后重新下载
//item.deleteFile 仅删除文件名为item.name 的文件
async function adDownloadFileAuto(item) {
let fs = await download.requestFileSystem(plus.io.PUBLIC_DOWNLOADS); //获取所要操作根目录File System
let url = item.url; //测试url---------
let newName = item.name;
let faceSyncEntry = await download.getDirectory({
//在PUBLIC_DOWNLOADS下定义人脸库同步文件夹"Face-Sync"
OriginPathEntry: fs.root,
newFileName: 'ad'
});
let newNameFileEntry = await download.resolveLocalFileSystemURL(faceSyncEntry.fullPath + newName).catch(e => {
console.log('目标文件可以操作', e);
});
if (newNameFileEntry) {
console.log('存在缓存的同名文件:', newNameFileEntry.fullPath);
if(item.deleteFile){
let delResult = await download.removeFile(newNameFileEntry); //删除已存在的文件
console.log("删除同名文件结果:",delResult)
return delResult
}
if(item.forceDownload){//当本地存在缓存时,是否强制删除后重新下载
let delResult = await download.removeFile(newNameFileEntry); //删除已存在的文件
}else{
return newNameFileEntry.fullPath //返回已缓存文件路径
}
}
let onProgresCallBack = function(e) {
//预留下载进度封装拓展
// console.log('下载中...', url, e);
};
let tempDownloadFilePath = await download.getDownloadFile({ url, onProgresCallBack }); //获取下载文件临时路径
let savedFilePath = await download.getSaveFile(tempDownloadFilePath); //将文件临时路径长久存储并清除
// let newName = item.user_id + '.' + (adType); //命名与android约定的文件名: [user_id].jpg------------
// newName = item.user_id + this.getName(url);
console.log(tempDownloadFilePath, 123456, savedFilePath.split('.')[1], savedFilePath);
let savedFilePathEntry = await download.resolveLocalFileSystemURL(savedFilePath); //获取下载后存储的文件Entry
let reNamePathEntry = await download.moveFileTo(savedFilePathEntry, faceSyncEntry, newName); //重命名文件到人脸库同步文件夹
// console.log(666,savedFilePath,newName,reNamePathEntry.fullPath)
return reNamePathEntry.fullPath;
}
function getDownloadFile({
url,
onProgresCallBack
}) {
return new Promise((rs, rj) => {
if (downloadTask) downloadTask.abort();
downloadTask = uni.downloadFile({
url: url,
timeout:60000,
// header:{
// "content-type":"image/png"
// },
success: res => {
if (res.statusCode == 200) {
console.log(url+" downloadFile:"+JSON.stringify(res))
rs(res.tempFilePath)
} else {
console.warn('下载失败--->', res);
console.warn('下载失败链接--->', url);
rj(res)
}
},
fail: failRes => {
console.warn('下载失败--->', failRes);
console.warn('下载失败链接--->', url);
rj(failRes)
}
})
downloadTask.onProgressUpdate(res => {
onProgresCallBack && onProgresCallBack(res);
})
})
}
//从临时路径文件获取持久文件
function getSaveFile(url) {
return new Promise((rs, rj) => {
uni.saveFile({
tempFilePath: url,
success: function(res_save) {
var savedFilePath = res_save.savedFilePath; //相对路径
// var absFilePath = plus.io.convertLocalFileSystemURL(savedFilePath); //绝对路径
// console.log('相对路径: ' + savedFilePath);
// console.log("绝对路径: " + absFilePath);
rs(savedFilePath)
// uni.getSavedFileList({
// success: function (res) {
// console.log(res.fileList);
// }
// });
},
fail: function(e) {
rj(e);
}
});
})
}
//根据本地文件url转换为fileEntry
function resolveLocalFileSystemURL(FilefullPath) {
return new Promise((rs, rj) => {
plus.io.resolveLocalFileSystemURL(FilefullPath,
function(fs) {
rs(fs)
},
function(err) {
rj(err)
});
})
}
// 请求本地文件系统对象Entry
// type:
// 应用私有资源目录,对应常量plus.io.PRIVATE_WWW,仅应用自身可读
// 应用私有文档目录,对应常量plus.io.PRIVATE_DOC,仅应用自身可读写
// 应用公共文档目录,对应常量plus.io.PUBLIC_DOCUMENTS,多应用时都可读写,常用于保存应用间共享文件
// 应用公共下载目录,对应常量plus.io.PUBLIC_DOWNLOADS,多应用时都可读写,常用于保存下载文件
//fs.root 为相应Entry
function requestFileSystem(type) {
return new Promise((rs, rj) => {
plus.io.requestFileSystem(type,
function(fs) {
rs(fs)
},
function(err) {
rj(err)
});
})
}
//移动文件(重命名)
function moveFileTo(fromPathEntry, toPathEntry, newFileName) {
return new Promise((rs, rj) => {
// remove this directory
// entry.remove( function ( entry ) {
// plus.console.log( "Remove succeeded" );
// }, function ( e ) {
// alert( e.message );
// } );
fromPathEntry.moveTo(toPathEntry, newFileName, function(entry) {
// console.log("新文件路径: " + entry.fullPath);
rs(entry)
}, function(e) {
console.log(e.message);
rj(e);
});
})
}
// 删除文件
function removeFile(entry){
// return new Promise(rs=>entry.remove( rs, rs ))
return new Promise((rs,rj)=>{
entry.remove( function ( entry ) {
console.log(entry)
rs( "Remove succeeded: "+entry.name );
}, function ( e ) {
rj( e.message );
} );
})
}
// 递归删除目录
function removeFileAll(entry){
return new Promise(rs=>entry.removeRecursively( rs, rs ))
}
//创建,读取文件
// 废弃
// function getFile(mFileEntry,path){
// // entry.getFile( path, flag, succesCB, errorCB );
// mFileEntry.getFile(path,{create:true}, function(fileEntry){
// fileEntry.file( function(file){
// var fileReader = new plus.io.FileReader();
// console.log("getFile:" + JSON.stringify(file));
// fileReader.readAsText(file, 'utf-8');
// fileReader.onloadend = function(evt) {
// console.log("evt:" + evt);
// console.log("evt.target" + evt.target);
// console.log(evt.target.result);
// rs(evt.target.result)
// }
// console.log( ">>>>>>>文件信息:"+file.name + ' : ' + file.size +" Kb <<<<<<<<");
// } );
// });
// }
// //废弃
// function writeFile(mFileEntry,path,msg){
// // Write data to file
// mFileEntry.getFile(path,{create:true}, function(fileEntry){
// fileEntry.createWriter( function ( writer ) {
// writer.onwrite = function ( e ) {
// console.log( "Write data success!" );
// rs(true)
// };
// // Write data to the end of file.
// // writer.seek( writer.length );
// writer.write(JSON.stringify(msg));
// }, function ( e ) {
// console.log( e.message );
// rj(false)
// } );
// });
// }
//获取file Entry
function mGetFile(mFileEntry,path){
return new Promise((rs,rj)=>{
mFileEntry.getFile(path,{create:true}, function(fileEntry){
rs(fileEntry)
});
})
}
//获取操作file
function mFile(fileEntry){
return new Promise((rs,rj)=>{
fileEntry.file( function(file){
var fileReader = new plus.io.FileReader();
// console.log("getFile:" + JSON.stringify(file));
fileReader.readAsText(file, 'utf-8');
fileReader.onloadend = function(evt) {
// console.log("evt:" + evt);
// console.log("evt.target" + evt.target);
// console.log(evt.target.result);
rs(evt.target.result)
}
console.log( ">>>>>>>文件信息:"+file.name + ' : ' + file.size +" B <<<<<<<<"+ JSON.stringify(file));
} );
})
}
//读取文件
function mCreateReader(fileEntry){
return new Promise((rs,rj)=>{
fileEntry.createWriter( function ( writer ) {
writer.onwrite = function ( e ) {
console.log( "Write data success!" );
rs("success")
};
// Write data to the end of file.
// writer.seek( writer.length );
writer.write(JSON.stringify(msg));
}, function ( e ) {
console.log( e.message );
rj(e.message)
} );
})
}
//写入文件
function mCreateWriter(fileEntry,msg){
return new Promise((rs,rj)=>{
fileEntry.createWriter( function ( writer ) {
writer.onwrite = function ( e ) {
console.log( "Write data success!" );
rs("success")
};
// Write data to the end of file.
// writer.seek( writer.length );
writer.write(JSON.stringify(msg));
}, function ( e ) {
console.log( e.message );
rj(e.message)
} );
})
}
// 从父目录下创建或打开子目录
function getDirectory({
OriginPathEntry,
newFileName
}) {
return new Promise((rs, rj) => {
// Retrieve an existing directory, or create it if it does not already exist
OriginPathEntry.getDirectory(newFileName, {
create: true,
exclusive: false
}, function(dir) {
// console.log("Directory Entry Name: " + dir.name);
rs(dir)
}, function(e) {
console.log(dir.name,e.message);
rj(e)
});
})
}
//获取该DirectoryEntry下所有文件和子目录
function getFileChildrenList(DirectoryEntry){
return new Promise((rs, rj) => {
// 创建读取目录信息对象
var directoryReader = DirectoryEntry.createReader();
directoryReader.readEntries( function( entries ){
var i,res=[];
for( i=0; i < entries.length; i++ ) {
// console.log( entries[i].name );
res.push( entries[i].name)
}
rs(res)
}, function ( e ) {
console.log( "Read entries failed: " + e.message );
rj(e.message)
} );
})
}
module.exports = {
getSaveFile,
getDownloadFile,
requestFileSystem,
resolveLocalFileSystemURL,
moveFileTo,
getDirectory,
removeFile,
removeFileAll,
readLocal,
writeLocal,
getFileChildrenList
}

25
zmt_module/src/main/java/io/dcloud/zmt_module/tcpServer/SocketHelper.java

@ -1,5 +1,8 @@
package io.dcloud.zmt_module.tcpServer;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
@ -11,11 +14,33 @@ import java.util.Arrays;
import java.util.Enumeration;
public class SocketHelper {
public static byte[] hexToBytes(String hex) {
int m = 0, n = 0;
int byteLen = hex.length() / 2; // 每两个字符描述一个字节
byte[] ret = new byte[byteLen];
for (int i = 0; i < byteLen; i++) {
m = i * 2 + 1;
n = m + 1;
int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));
ret[i] = Byte.valueOf((byte) intVal);
}
return ret;
}
public static String getMessageByReadLine(String message) {
message = message + "\n";
return message;
}
public static Bitmap base64ToBitmap(String base64Data) {
byte[] bytes = new byte[0];
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
bytes = android.util.Base64.decode(base64Data, android.util.Base64.DEFAULT);
}
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
public static byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];

22
zmt_module/src/main/java/io/dcloud/zmt_module/tcpServer/TCPTask.java

@ -1,7 +1,13 @@
package io.dcloud.zmt_module.tcpServer;
import android.os.Looper;
import android.os.Message;
import com.alibaba.fastjson.JSONObject;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.zmt_module.SocketConfig;
import io.dcloud.zmt_module.tcpServer.SocketHelper;
@ -15,13 +21,21 @@ public class TCPTask {
void tcpCallback(Object object);
}
TcpServer server = new TcpServer();
public TcpServer server ;
Thread myThread;
Boolean stopThread = false;
// TCP task
public void sendTcpCallBack(String send_msg){
send_msg = SocketHelper.getMessageByReadLine(send_msg);
server.sendMessageInThreadPrinter(send_msg, SocketConfig.UTF_8);//回发消息
}
public void task(final Integer port, final UniJSCallback uniJSCallback){
// Android 4.0 之后不能在主线程中请求HTTP请求
// System.out.println("AsyncTask thread running... ==>>>44444444:"+port+ server.isServerBound());
this.server = new TcpServer();
// this.server = server.initSocket(port,uniJSCallback);
myThread = new Thread(new Runnable() {
@Override
@ -42,9 +56,9 @@ public class TCPTask {
if(tcp_receive_message!=null){
System.out.println(TAG+"接收消息:"+tcp_receive_message);
String send_msg = "App received tcp message!"; //回发socket消息确认接收
send_msg = SocketHelper.getMessageByReadLine(send_msg);
server.sendMessage(send_msg, SocketConfig.UTF_8);//回发消息
// String send_msg = "5501a23070b6"; //回发socket消息确认接收
// send_msg = SocketHelper.getMessageByReadLine(send_msg);
// server.sendMessage(send_msg, SocketConfig.UTF_8);//回发消息
JSONObject data = new JSONObject();
data.put("threadID", Thread.currentThread().getId());

204
zmt_module/src/main/java/io/dcloud/zmt_module/tcpServer/TcpServer.java

@ -14,25 +14,36 @@ import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.zmt_module.SocketConfig;
import io.dcloud.zmt_module.tcpServer.SocketHelper;
public class TcpServer {
// 私有变量
private String TAG = "zmt---";
private ServerSocket mServerSocket;
public ServerSocket mServerSocket;
// private DatagramSocket mServerSocket;
private Socket mServer;
public Socket mServer;
public Socket currentServer;
private OutputStream mOutStream;
private PrintWriter mPrinter;
public OutputStream mOutStream;
public PrintWriter mPrinter;
public InputStream mInputStream;
public BufferedInputStream mBufferedInputStream;
public InputStreamReader mInputStreamReader;
public BufferedReader mBufferedReader;
public String MySend = null;
private ExecutorService mExecutorService;
public void SocketUDPClientUtil() {
mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
}
private InputStream mInputStream;
private BufferedInputStream mBufferedInputStream;
private InputStreamReader mInputStreamReader;
private BufferedReader mBufferedReader;
/**
*使用本机ip 建立socket server
@ -42,7 +53,8 @@ public class TcpServer {
public void initSocket(int port, UniJSCallback uniJSCallback){
System.out.println(TAG+"initSocket");
try{
// if (mServerSocket != null) { mServerSocket.close(); mServerSocket = null; }
this.SocketUDPClientUtil();
if (mServerSocket != null) { mServerSocket.close(); mServerSocket = null; }
if (mServerSocket==null){
mServerSocket = new ServerSocket(port);
@ -58,38 +70,8 @@ public class TcpServer {
data.put("ip", SocketHelper.getIPAddressForNetwork());
uniJSCallback.invokeAndKeepAlive(data);
// while (true){
// String tcp_receive_message = receiveMessage(SocketConfig.UTF_8);//接收消息
//
// if(tcp_receive_message!=null){
// System.out.println(TAG+"接收消息:"+tcp_receive_message);
// String send_msg = "App received tcp message!"; //回发socket消息确认接收
// send_msg = SocketHelper.getMessageByReadLine(send_msg);
// sendMessage(send_msg, SocketConfig.UTF_8);//回发消息
//
// JSONObject data_receive = new JSONObject();
// data_receive.put("threadID", Thread.currentThread().getId());
// data_receive.put("threadName", Thread.currentThread().getName());
//// data.put("message", server.);
//// data.put("message", tcp_receive_message);
// data_receive.put("message", tcp_receive_message);
//// myCallback.tcpCallback(data);
//// myTcpCallback.tcpCallback(data);//回调到zmtClass给uni端
//
// uniJSCallback.invokeAndKeepAlive(data_receive);
// }
//
// try {
// Thread.sleep(1000); //定义休眠时间
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }
}
// if(mServerSocket==null){
// //自己IP收信
//// IPAddress ip = IPAddress.Parse("192.168.1.96");
@ -147,6 +129,12 @@ public class TcpServer {
// return null;
// }
mServer = mServerSocket.accept();
mServer.setKeepAlive(true);
// mServer.setTcpNoDelay(true);
// mServer.setSoTimeout(5000);
// mServer.setOOBInline(true);
System.out.println("当前连接客户端信息:"+mServer.getInetAddress()+" "+mServer.getKeepAlive()+" "+mServer.getLocalSocketAddress()+ " "+mServer.getRemoteSocketAddress() );
this.currentServer = mServer; //赋值当前通信socket
mInputStream = mServer.getInputStream();
byte[] data = SocketHelper.toByteArray(mInputStream);
@ -181,25 +169,79 @@ public class TcpServer {
}
// 发送消息
public void sendMessage(String message,String charsetName){
public void sendMessage(final String message,final String charsetName){
System.out.println(TAG+"sendMessage ing..888888."+mServer.getLocalSocketAddress()+
" /n"+ mServer.isClosed() + mServer.isConnected()
);
// mServer = this.currentServer;
if(mServer != null){
System.out.println(TAG+"sendMessage ing...");
try {
mOutStream = mServer.getOutputStream();
System.out.println(TAG+"sendMessage ing...1");
mPrinter = new PrintWriter(new OutputStreamWriter(mOutStream,Charset.forName(charsetName)));
System.out.println(TAG+"sendMessage ing...2");
mPrinter.println(message);
System.out.println(TAG+"sendMessage ing...3");
// mOutStream.write("beat666".getBytes(Charset.forName(charsetName)));
// mOutStream.flush();
mPrinter.flush();
System.out.println(TAG+"发送成功 :"+message);
} catch (IOException e) {
System.out.println(TAG+"tcp server sendMessage err :"+message);
System.out.println(TAG+"tcp server sendMessage err :"+e);
e.printStackTrace();
}
System.out.println(TAG+"TCP发送成功 :"+message);
}else{
System.out.println(TAG+"无法发送消息,当前没有客户端连接。");
}
}
public void sendMessageInThreadPrinter(final String message, final String charsetName){
Runnable mRunnable = new Runnable() {
@Override
public void run() {
try {
mOutStream = mServer.getOutputStream();
mPrinter = new PrintWriter(new OutputStreamWriter(mOutStream,Charset.forName(charsetName)));
// mPrinter.println(message);
// mPrinter.flush();
// mOutStream.write(message.getBytes(Charset.forName(charsetName)));
mOutStream.write(SocketHelper.hexToBytes(message));
mOutStream.flush();
System.out.println(TAG+"TCP发送成功 :"+message);
} catch (IOException e) {
System.out.println(TAG+"tcp server sendMessage err :"+e);
e.printStackTrace();
}
}
};
mExecutorService.execute(mRunnable);
}
public void sendMessageInServer(String message,String charsetName){
final byte[] msg ;
msg = message.getBytes(Charset.forName(charsetName));
Runnable mRunnable = new Runnable() {
@Override
public void run() {
try {
mServer.getOutputStream().write(msg);
mServer.getOutputStream().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
};
mExecutorService.execute(mRunnable);
}
// 关闭连接
public void close(){
try {
@ -226,4 +268,80 @@ public class TcpServer {
e.printStackTrace();
}
}
/**
*使用本机ip 建立socket server
* @param port 端口号0-65535
*ServerSocket mServerSocket,Socket mServer,
*/
public void initSocket2(int port, UniJSCallback uniJSCallback){
System.out.println(TAG+"initSocket");
this.SocketUDPClientUtil();
try{
if (mServerSocket != null) { mServerSocket.close(); mServerSocket = null; }
if (mServerSocket==null){
mServerSocket = new ServerSocket(port);
mServerSocket.setReuseAddress(true);
// mServerSocket.bind(new InetSocketAddress(port));
InetAddress inetAddress = InetAddress.getLocalHost(); //本机地址
System.out.println(TAG+"tcp server 建立完成:host name"+inetAddress.getHostName()+"\n ---host address:" +
inetAddress.getHostAddress()+" , address:"+inetAddress.getAddress().toString()+" 端口:"+port+ "----"+ SocketHelper.getIPAddressForNetwork());
com.alibaba.fastjson.JSONObject data = new com.alibaba.fastjson.JSONObject();
data.put("port", port);
data.put("ip", SocketHelper.getIPAddressForNetwork());
uniJSCallback.invokeAndKeepAlive(data);
while (true){
String tcp_receive_message = receiveMessage(SocketConfig.UTF_8);//接收消息
if (this.MySend!=null){
MySend = SocketHelper.getMessageByReadLine(MySend);
sendMessage(MySend, SocketConfig.UTF_8);//回发消息
}
if(tcp_receive_message!=null){
System.out.println(TAG+"接收消息:"+tcp_receive_message);
String send_msg = "App received tcp message!"; //回发socket消息确认接收
send_msg = SocketHelper.getMessageByReadLine(send_msg);
// sendMessage(send_msg, SocketConfig.UTF_8);//回发消息
JSONObject data_receive = new JSONObject();
data_receive.put("threadID", Thread.currentThread().getId());
data_receive.put("threadName", Thread.currentThread().getName());
// data.put("message", server.);
// data.put("message", tcp_receive_message);
data_receive.put("message", tcp_receive_message);
// myCallback.tcpCallback(data);
// myTcpCallback.tcpCallback(data);//回调到zmtClass给uni端
uniJSCallback.invokeAndKeepAlive(data_receive);
}
try {
Thread.sleep(1000); //定义休眠时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}catch (IOException e){
if(e.getMessage().equals("bind failed: EADDRINUSE (Address already in use)")){
System.out.println("已初始化过TCP,忽略该操作:"+e.getMessage());
JSONObject _data = new JSONObject();
_data.put("code",0);
_data.put("toast","已初始化过TCP,请勿重复执行初始化操作。");
uniJSCallback.invokeAndKeepAlive(_data);
}else{
e.printStackTrace();
}
}
}
}

64
zmt_module/src/main/java/io/dcloud/zmt_module/zmtClass.java

@ -16,8 +16,9 @@ import static io.dcloud.zmt_module.tcpServer.SocketHelper.getIPAddressForNetwork
public class zmtClass extends UniModule {
String TAG = "module plugin";
TCPTask myTCPTask = new TCPTask();
// final AbsSDKInstance uniSDK = this.mUniSDKInstance;//定义uniSDK
TCPTask myTask = new TCPTask();
public TCPTask myTask = new TCPTask();
//run ui thread
@UniJSMethod(uiThread = true)
public void initTcp(JSONObject options, final UniJSCallback callback) {
@ -31,15 +32,16 @@ public class zmtClass extends UniModule {
}
//开启TCP,传入jsCallback
if(myTask!=null){
myTask.task(port, callback);
}else{
JSONObject data = new JSONObject();
data.put("code", "0");
data.put("toast", "请勿重复开启");
callback.invokeAndKeepAlive(data);
}
// myTask = new TCPTask();
myTCPTask.task(port, callback);
// if(myTask!=null){
// myTask.task(port, callback);
// }else{
// JSONObject data = new JSONObject();
// data.put("code", "0");
// data.put("toast", "请勿重复开启");
// callback.invokeAndKeepAlive(data);
// }
// 全局回调
@ -48,15 +50,16 @@ public class zmtClass extends UniModule {
// uniSDK.fireGlobalEventCallback("myEvent", params);//发送全局参数直接回调
}
//run JS thread
@UniJSMethod(uiThread = true)
public void getIP(JSONObject options, final UniJSCallback callback){
public void sendTcp(JSONObject options, final UniJSCallback callback){
Log.e(TAG, "UniJSMethod getIP");
JSONObject data = new JSONObject();
data.put("code", "0");
try {
data.put("ip", getIPAddressForNetwork());
} catch (SocketException e) {
e.printStackTrace();
@ -65,9 +68,42 @@ public class zmtClass extends UniModule {
callback.invokeAndKeepAlive(data);
}
@UniJSMethod(uiThread = true)
public void closeTcp(JSONObject options, final UniJSCallback callback){
Log.e(TAG, "sendTcpCallBack ");
JSONObject data = new JSONObject();
String msg = "5501a23070b6";
if (options.getString("message")!=null){
msg = options.getString("message");
}
data.put("code", "0");
data.put("toast", "sendTcpCallBack: "+msg);
if(myTCPTask!=null){
myTCPTask.sendTcpCallBack(msg);
}
callback.invokeAndKeepAlive(data);
}
@UniJSMethod(uiThread = true)
public void closeTcp2(JSONObject options, final UniJSCallback callback){ //TODO 需优化暂勿用
Log.e(TAG, "testSyncFunc--zmt2");
JSONObject data = new JSONObject();
data.put("code", "0");
data.put("toast", "closeTcp");
// System.out.println("7777777"+myTCPTask.toString());
if(myTCPTask!=null){
myTask.closeTask();
myTask = null;
}
callback.invokeAndKeepAlive(data);
}
//run JS thread
@UniJSMethod(uiThread = true)
public void closeTcp(JSONObject options, final UniJSCallback callback){ //TODO 需优化暂勿用
public void closeTcp1(JSONObject options, final UniJSCallback callback){ //TODO 需优化暂勿用
Log.e(TAG, "testSyncFunc--zmt2");
JSONObject data = new JSONObject();
data.put("code", "0");

Loading…
Cancel
Save