安卓使用TCP/Ip協議傳輸資料
阿新 • • 發佈:2019-02-07
由於要和別人的客控系統做對接,他們使用的是TCP協議,我傳送,他返回,注意設定超時package com.example.testtcp; import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { EditText editText; Button button; Socket socket; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = findViewById(R.id.edit); button = findViewById(R.id.button); try { socket = new Socket("192.168.2.227", 2023); // 設定10秒之後即認為是超時 socket.setSoTimeout(10000); } catch (Exception e) { e.printStackTrace(); } button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { Send(editText.getText().toString()); } }).start(); } }); } private void Send(String s) { try { // 傳送資料給服務端 OutputStream outputStream = socket.getOutputStream(); outputStream.write(s.getBytes("gb2312")); // socket.shutdownOutput(); // 等待伺服器傳送資料,讀取資料(超時異常) DataInputStream br = new DataInputStream(socket.getInputStream()); byte[] b = new byte[1024]; int length = br.read(b); String Msg = new String(b, 0, length, "gb2312"); System.out.println(Msg + " 接收到伺服器的資料"); } catch (UnknownHostException e) { System.out.println("UnknownHost 來自伺服器的資料"); e.printStackTrace(); } catch (IOException e) { System.out.println("IOException 來自伺服器的資料"); e.printStackTrace(); } } @Override protected void onDestroy() { try { socket.shutdownOutput(); } catch (IOException e) { e.printStackTrace(); } super.onDestroy(); } }