在连接服务器时可以用Handler进行通信下面举列说明:
我在连接服务器时的代码,写在单独的方法中:
在线程中实例化一个Handler会自动绑定当前线程,加粗的地方是将message发出去
/** * 连接 * * @return*/
public boolean connect(final Handler handler) {
if (socket == null || socket.isClosed()) {
new Thread(new Runnable() {
@Override public void run() {
try {
socket = new Socket(dsName, dstPort);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
throw new RuntimeException("连接错误: " + e.getMessage());
}
try {
// 输入流,为了获取客户端发送的数据 InputStream is = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
final String result = new String(buffer, 0, len);
Message msg = Message.obtain();
msg.obj = result;
msg.what = STATE_FROM_SERVER_OK;
handler.sendMessage(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
return true;
}
在MainActivity中获取Handler的信息:
private Handler mHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case TcpManager.STATE_FROM_SERVER_OK:
String result = (String) msg.obj;
//这里可以将你得到的消息打印出来,或者怎么用都行
break;
default:
break;
}
};
};