@Override public void run() { try { ... ... inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytes; while (true) { //讀取數據 bytes = inputStream.read(buffer); if (bytes > 0) { final byte[] data = new byte[bytes]; System.arraycopy(buffer, 0, data, 0, bytes); text_msg.post(new Runnable() { @Override public void run() { text_msg.setText(getResources().getString(R.string.get_msg)+new String(data)); } }); } } } catch (IOException e) { e.printStackTrace(); text_state.post(new Runnable() { @Override public void run() { text_state.setText(getResources().getString(R.string.connect_error)); } }); }
/** * 發送數據 * * @param msg */ public void sendMsg(final String msg) { byte[] bytes = msg.getBytes(); if (outputStream != null) { try { //發送數據 outputStream.write(bytes); text_msg.post(new Runnable() { @Override public void run() { text_msg.setText(getResources().getString(R.string.send_msgs)+msg); } }); } catch (IOException e) { e.printStackTrace(); text_msg.post(new Runnable() { @Override public void run() { text_msg.setText(getResources().getString(R.string.send_msg_error)+msg); } }); } } }
——————————————————————————————java