Android TCP的客戶端(請求的傳送和響應結果接收)
阿新 • • 發佈:2019-01-08
Android TCP客戶端傳送請求並接收響應
<span style="font-size:14px;"> import android.util.Log; import com.changhong.electric_controll.UDPResponseCallback; import com.changhong.electric_controll.connect.entity.entity.EquipResponse; import com.changhong.electric_controll.connect.entity.parser.QueryOrderBuilder; import com.changhong.electric_controll.util.ByteUtils; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by zhangning on 2016/5/24. */ public class TCPReceive extends Thread{ private Socket connectsocket; private String IPAddress; private int Port; private UDPResponseCallback mUDPResponseCallback; //自定義介面,用於再activity中處理接收的結果,如果不用,可以直接刪除 private boolean isSuccess=false; private String lastResult; private byte[] senddata; private byte[] acceptdata; private int callbacktype; private static long INTERVAL_TIME=15*1000; public TCPReceive(UDPResponseCallback udpResponseCallback,Socket socket,String IPAddress,int port,byte[] senddata,int callbacktype){ this.connectsocket=socket; this.IPAddress=IPAddress; this.Port=port; this.mUDPResponseCallback=udpResponseCallback; this.senddata=senddata; this.callbacktype=callbacktype; } public TCPReceive(Socket socket,String IPAddress,int port,byte[] senddata,int callbacktype){ this.connectsocket=socket; this.IPAddress=IPAddress; this.Port=port; this.senddata=senddata; this.callbacktype=callbacktype; } @Override public void run() { if(callbacktype==0){ onebyone(); } else if(callbacktype == 1){ moretomore(); } else if(callbacktype==2){ equitupload(); } } /**一應一答模式(所謂的短連線模式)**/ public void onebyone(){ buildConnect(); //建立與伺服器的連線 if(isSuccess){ senddata(senddata, connectsocket); } } /**迴圈傳送請求和接收響應**/ public void moretomore(){ buildConnect(); //建立與伺服器的連線 while(true) { try{ if(connectsocket.isClosed()){ break; } if (isSuccess) { senddata(senddata, connectsocket); } Thread.sleep(INTERVAL_TIME); }catch(InterruptedException e){ e.printStackTrace(); } } } /**迴圈接收伺服器傳過來的資料**/ public void equitupload(){ buildConnect(); //建立與伺服器的連線 if(isSuccess) { while (true) { try{ Thread.sleep(1000); }catch(InterruptedException e){ e.printStackTrace(); } Log.i("Data", "接收資料"); if(!connectsocket.isClosed()) { acceptdata(connectsocket); Log.i("Data", "接收響應資料結束++++++++++++++++"); } else { break; } } } } /**建立與伺服器的連線併發送請求**/ public void buildConnect(){ try { Log.i("Data", " socket begin connect ++++++++++"); Log.i("Data","tcp connect ,ip = "+IPAddress+"Port = "+Port); Log.i("Data","the send data="+ByteUtils.bytesToHexString(senddata)); //connectsocket=new Socket(IPAddress,Port); //connectsocket.setSoTimeout(10*1000); //設定連線超時時間 Log.i("Data", "connectsocket.isConnected=" + connectsocket.isConnected()); //是否關閉 Log.i("Data", "connectsocket.isClosed=" + connectsocket.isClosed()); //是否連線 Log.i("Data", "connectsocket.isInputShutdown=" + connectsocket.isInputShutdown()); //是否關閉輸入流 Log.i("Data", "connectsocket.isOutputShutdown=" + connectsocket.isOutputShutdown()); //是否關閉輸出流 Log.i("Data", "連線請求已傳送"); if(connectsocket.isConnected()&&(!connectsocket.isClosed())){ //表明當前連線成功 Log.i("Data", "連線成功,準備傳送資訊"); isSuccess = true; } else{ try { Log.i("Data","斷開連線,重新連線"); Thread.sleep(1000); connectsocket=new Socket(IPAddress,Port); if(connectsocket.isConnected()&&(!connectsocket.isClosed())){ Log.i("Data","嘗試重新連線成功"); isSuccess=true; } else{ Log.i("Data","嘗試重新連線失敗"); isSuccess = false; mUDPResponseCallback.onResponse(null,isSuccess); //直接返回結果 return; } }catch(InterruptedException e){ isSuccess=false; mUDPResponseCallback.onResponse(null,isSuccess); //將返回結果傳遞給callback去解析 e.printStackTrace(); } return; } }catch(IOException e){ isSuccess=false; mUDPResponseCallback.onResponse(null,isSuccess); //將返回結果傳遞給callback去解析 e.printStackTrace(); } } /**傳送資料**/ public void senddata(byte[] senddata,Socket connectsocket1){ synchronized(this) { try { ByteArrayInputStream byteArrayinputstream = new ByteArrayInputStream(senddata); Log.i("Data", "read line......" + ByteUtils.bytesToHexString(senddata)); if (byteArrayinputstream != null) { BufferedReader in = new BufferedReader(new InputStreamReader(byteArrayinputstream)); Log.i("Data", "向伺服器傳送資料,傳送時間="+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); if (connectsocket1.isClosed()) { connectsocket1.close(); } else { connectsocket1.getOutputStream().write(senddata); Log.i("Data", "獲取輸出流成功"); } } } catch (IOException e) { e.printStackTrace(); } } } /**接收資料**/ public byte[] acceptdata(Socket connectsocket) { byte[] acceptdata1=null; try { InputStream istream=null; //Thread.sleep(1000); if (connectsocket.isConnected()) { if (!connectsocket.isInputShutdown()) { istream=connectsocket.getInputStream(); int datalength=istream.available(); Log.i("Data","接收到的位元組數"+datalength); if(datalength >0) { acceptdata1 = new byte[datalength]; istream.read(acceptdata1); if (acceptdata1 != null) { isSuccess = true; lastResult = ByteUtils.bytesToHexString(acceptdata1); Log.i("Data", "the lastresult=" + lastResult); mUDPResponseCallback.onResponse(lastResult, isSuccess); //將返回結果傳遞給callback去解析 } } } else { isSuccess=false; Log.i("Data", "connectsocket 失敗 isInputShutdown=false"); mUDPResponseCallback.onResponse(null, isSuccess); //將返回結果傳遞給callback去解析 } } } catch(IOException e){ e.printStackTrace(); } return acceptdata1; } }</span><strong style="font-size: 12pt;"> </strong>