由于项目实现手机连接网口打印机进行打印,关于5+网口打印的文档demo少之又少,且都有致命bug。先贴下原demo。
function testSocket(){
if (plus.os.name == “Android”) {
var Socket = plus.android.importClass(“java.net.Socket”);
var PrintWriter = plus.android.importClass(“java.io.PrintWriter”);
var BufferedWriter = plus.android.importClass(“java.io.BufferedWriter”);
var OutputStreamWriter = plus.android.importClass(“java.io.OutputStreamWriter”);
var BufferedReader = plus.android.importClass(“java.io.BufferedReader”);
var InputStreamReader = plus.android.importClass(“java.io.InputStreamReader”);
var socket = new Socket("192.168.23.8", 8080);
var outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
var bufferWriter = new BufferedWriter(outputStreamWriter);
var out = new PrintWriter(bufferWriter, true);
out.println("Conneted...");
var inputStreamReader = new InputStreamReader(socket.getInputStream());
var br = new BufferedReader(inputStreamReader);
var msg = br.readLine();
//while(true)
{
if(msg != null)
{
console.log(msg);
}
//msg = br.readLine();
}
}
//console.log(mac);
alert("Done");
}
当时搜到demo 时,感觉贼开行,因为这可以省去我很多时间。可实际用于开发的时候才发现,官方demo坑是真的多。。demo是连接socket进行打印但几分钟不操作会断开连接打印失败,如果连接错误的ip,会阻塞进程,因为 程序一直在连接,也不会超时,造成进程阻塞,项目崩溃。。这可不行,于是尝试在网上搜解决方法,坑爹的是网上千篇一律都是官方demo,坑还是一样。走投无路只能尝试去理解原生类库的用法,终于走到了解决的方法。。。
var Socket = plus.android.importClass(“java.net.Socket”);
var PrintWriter = plus.android.importClass(“java.io.PrintWriter”);
var BufferedWriter = plus.android.importClass(“java.io.BufferedWriter”);
var OutputStreamWriter = plus.android.importClass(“java.io.OutputStreamWriter”);
var BufferedReader = plus.android.importClass(“java.io.BufferedReader”);
var InputStreamReader = plus.android.importClass(“java.io.InputStreamReader”);
var SocketAddress = plus.android.importClass(“java.net.InetSocketAddress”);
//测试改良
var StrictMode = plus.android.importClass(“android.os.StrictMode”);
var Build = plus.android.importClass(“android.os.Build”);
if (Build.VERSION.SDK_INT > 9) {
var policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//改良socket连接
var socket = new Socket();
var socketAddr = new SocketAddress(ip,port);
socket.connect(socketAddr,2000);
//改良socket连接
var outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
var bufferWriter = new BufferedWriter(outputStreamWriter);
var out = new PrintWriter(bufferWriter, true);
out.println("好坑啊");
socket.close();//这个很重要,不然后会出现重复连接卡死程序
以上demo解决了socket中断和阻塞进程,换成了socket.connect()来连接socket,并设置超时时间就不会阻塞进程了。但是!又一个坑出来了,打印之后你会发现中文乱码!!中文,然后又去搜解决中文乱码的方法,果然网上也没说怎么解决中文乱码的方法。最后还得去理解java方法类库。。还真的有。。。
把 var outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
改成 var outputStreamWriter = new OutputStreamWriter(socket.getOutputStream(),'gbk');
ok!打印中文实现。真希望官方能给出个完善的demo出来,让后来的开发者少走点弯路,特此写下这篇文章,不用谢,请叫我雷锋