用socket连接服务器的时候,需要在子线程进行网络请求,请求完成之后可以通过Handler来处理主线程应该得到的通知(更新view)
private void StartRequestFromSocket(final int mycho) { new Thread() { public void run() { try { SendRequest(mycho); } catch (Exception e) { e.printStackTrace(); } } }.start(); } public void SendRequest(int mycho) { String sendString="sendString"; try { socket = new Socket(IpAddress, Port); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // 由系统标准输入设备构造BufferedReader对象 PrintWriter write = new PrintWriter(socket.getOutputStream()); // 由Socket对象得到输出流,并构造PrintWriter对象 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); write.println(sendString); write.flush(); getS = in.readLine(); System.out.println("Server:" + getS); mHandler.sendEmptyMessage(mycho); } catch (UnknownHostException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
时间: 2024-10-20 15:58:48