先看效果如下:
工程结构如下:
///xml中的布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/txt_ip" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="IP:" /> <EditText android:id="@+id/edit_ip" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="127.0.0.1" /> <TextView android:id="@+id/txt_port" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Port:" /> <EditText android:id="@+id/edit_port" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="1234" /> <Button android:id="@+id/btn_connect" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Connect" /> <TextView android:id="@+id/txt_receive" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Receive:" /> <EditText android:id="@+id/edit_receive" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" android:lines="2" /> <TextView android:id="@+id/txt_send" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Send:" /> <EditText android:id="@+id/edit_send" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /> <Button android:id="@+id/btn_send" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Send" /> </LinearLayout>
///MainActivity中的实现
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import android.app.Activity; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class TcpClientActivity extends Activity { private final String TAG="TcpClientActivity"; //About the ui controls private EditText edit_ip = null; private EditText edit_port = null; private Button btn_connect = null; private EditText edit_receive = null; private EditText edit_send = null; private Button btn_send = null; private boolean isConnected = false; //About the socket private Socket client = null; private OutputStream outputStream=null; private InputStream inputStream=null; private boolean thread_flag=true; private boolean thread_read_flag=true; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init(){ edit_ip = (EditText)findViewById(R.id.edit_ip); edit_port = (EditText)findViewById(R.id.edit_port); edit_receive = (EditText)findViewById(R.id.edit_receive); edit_send = (EditText)findViewById(R.id.edit_send); btn_connect = (Button)findViewById(R.id.btn_connect); btn_connect.setOnClickListener(new BtnConnectOnClickListener()); btn_send = (Button)findViewById(R.id.btn_send); btn_send.setOnClickListener(new btnSendOnClickListener()); //Load the datas from share preferences SharedPreferences sharedata = getSharedPreferences("data", 0); String ip = sharedata.getString("ip", "127.0.0.1"); String port = sharedata.getString("port", "1234"); edit_ip.setText(ip); edit_port.setText(port); } //Click here to connect class BtnConnectOnClickListener implements OnClickListener{ public void onClick(View v) { // TODO Auto-generated method stub try { if (false == isConnected) { InetAddress serverAddr = InetAddress.getByName(edit_ip .getText().toString());// TCPServer.SERVERIP client = new Socket(serverAddr, Integer.valueOf(edit_port .getText().toString())); btn_connect.setText("Disconnect"); outputStream = client.getOutputStream(); inputStream = client.getInputStream(); isConnected = true; thread_read_flag = true; new Thread(new InputStreamThread()).start(); } else { btn_connect.setText("Connect"); edit_receive.setText(""); edit_send.setText(""); client.close(); isConnected = false; thread_read_flag = false; } } catch (NumberFormatException e) { // TODO Auto-generated catch block Log.d(TAG, e.getMessage()); } catch (IOException e) { // TODO Auto-generated catch block Log.d(TAG, e.getMessage()); } } } // This is to send bytes to server class btnSendOnClickListener implements OnClickListener{ public void onClick(View v) { // TODO Auto-generated method stub Log.d(TAG, "sendText:"+edit_send.getText().toString()); try { outputStream.write(edit_send.getText().toString().getBytes()); outputStream.flush(); } catch (NumberFormatException e) { // TODO Auto-generated catch block Log.d(TAG, e.getMessage()); } catch (IOException e) { // TODO Auto-generated catch block Log.d(TAG, e.getMessage()); } } } //This is to read the bytes from server class InputStreamThread implements Runnable{ public void run() { byte[] buffer = new byte[1024]; // TODO Auto-generated method stub final StringBuilder sb = new StringBuilder(); try { while(thread_read_flag){ int readSize = inputStream.read(buffer); Log.d(TAG,"readSize:"+readSize); //Server is stoping if(readSize == -1){ thread_read_flag = false; //inputStream.close(); runOnUiThread(new Runnable(){ public void run() { // TODO Auto-generated method stub btn_connect.setText("Connect"); edit_receive.setText(""); } }); inputStream.close(); isConnected = false; break; } if(readSize == 0) continue; //Update the receive editText sb.append(new String(buffer,0,readSize)); runOnUiThread(new Runnable(){ public void run() { // TODO Auto-generated method stub edit_receive.setText(sb.toString()); } } ); } } catch (IOException e) { // TODO Auto-generated catch block Log.d(TAG, e.getMessage()); } } } @Override protected void onDestroy() { // TODO Auto-generated method stub Log.d(TAG,"onDestroy"); //Store the data in the viewText, for you can load that data next time when launched Editor sharedata = getSharedPreferences("data", 0).edit(); sharedata.putString("ip",edit_ip.getText().toString()); sharedata.putString("port",edit_port.getText().toString()); sharedata.commit(); super.onDestroy(); } }
//AndroidManifest.xml文件里的内容
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.lujianfei.tcpclient" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".TcpClientActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
要使android支持网络必须加入
<category android:name="android.intent.category.LAUNCHER" />