求教关于Socket线程执行中疑惑

happycompiler 2016-10-01 08:40:21
业务上需实现通过wifi打印机打印功能,子线程创建的socket对象如何返回给主线程?Android新手求教
代码如下:

//调用
WifiPrinterService wifiprinter = new WifiPrinterService("192.168.0.1", 10000, "GBK");
wifiprinter.printText("\t\t Text to The Printer");

public class WifiPrinterService {
// 定义编码方式
private static String encoding = null;
private String ip;
private int port;
private Socket sock = null;
// 通过socket流进行读写
private OutputStream socketOut = null;
private OutputStreamWriter writer = null;

public Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
if (msg.what == 0x100) {
sock = (Socket) msg.obj;
}
}
};
public WifiPrinterService(String ip, int port, String encoding) {
try {
this.ip = ip;
this.port = port;
boolean isSocketConnect = false;
if (sock != null) {
closeIOAndSocket();
} else {
WifiConn.start();
}
sock.setSoTimeout(1000 * 3); //sock对象为null异常
socketOut = new DataOutputStream(sock.getOutputStream());
this.encoding = encoding;
writer = new OutputStreamWriter(socketOut, encoding);
isSocketConnect = true;
} catch (Exception e) {
Log.e("king", e.toString());
}
}

Thread WifiConn = new Thread() {
@Override
public void run() {
try {
Socket sock = new Socket(ip, port);

Message msg = new Message();
msg.what = 0x100;
msg.obj = sock;
myHandler.sendMessage(msg);

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};

/**
* 打印文字
*/
public void printText(String text) throws IOException {
String s = text;
byte[] content = s.getBytes("gbk");
socketOut.write(content);
socketOut.flush();
}
}
...全文
235 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

80,490

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧