博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android开发笔记03
阅读量:6714 次
发布时间:2019-06-25

本文共 7166 字,大约阅读时间需要 23 分钟。

先看效果如下:

 

 

工程结构如下:

///xml中的布局文件

 

///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文件里的内容

要使android支持网络必须加入

 

转载于:https://www.cnblogs.com/kevin-tyc/p/3322489.html

你可能感兴趣的文章
Java中创建对象的5种不同方法
查看>>
Supervisor安装
查看>>
自建框架知识点一命名空间和自动加载
查看>>
21_css布局2_浮动布局.html
查看>>
DateUtils 单元下的公用函数目录
查看>>
构建高效安全的Nginx Web服务器
查看>>
jQuery 练习[二]: 获取对象(1) - 基本选择与层级
查看>>
GNS3桥接真机网卡
查看>>
Web服务之LNMMP架构及动静分离实现
查看>>
centos6.4搭建zabbix
查看>>
Nginx+Keepalived实现
查看>>
安装python的easy_install和pip
查看>>
android SQLite
查看>>
Apache for Load Banlance
查看>>
Sublime Text 2 快捷键用法大全
查看>>
放弃redis使用mongodb做任务队列支持增删改管理
查看>>
G口与S口的区别
查看>>
甲骨文拒绝SAP 2.72亿美元赔偿要求重审
查看>>
FLEX3中应用CSS完全详解手册
查看>>
Windows7添加usb3.0驱动
查看>>