Android Studio项目——TCP客户端

目录

一、TCP客户端UI

1、UI展示

2、xml代码

二、TCP客户端数据发送

三、TCP客户端数据接收


一、TCP客户端UI

1、UI展示

Android Studio项目——TCP客户端_第1张图片

2、xml代码




    

二、TCP客户端数据发送

public void Client_SendMessage(){
        try {
            Socket client = new Socket("192.168.124.6",8089);
            OutputStream out = client.getOutputStream();
            out.write("meng".getBytes());

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public void btn_client_send_clicked(View v){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Client_SendMessage();
            }
        }).start();
    }

三、TCP客户端数据接收

textView1 = findViewById(R.id.text_view);
textView1.setText("数据接收框");
textView2 = findViewById(R.id.text_view2);
textView2.setText("0");
new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Socket client = new Socket("192.168.124.6",8089);
                        int len;
                        InputStream in = client.getInputStream();
                        byte[] data = new byte[128];
                        len = in.read(data);
                        String str = new String(data,0,len);
                        Message msg2 = new Message();
                        Bundle b = new Bundle();
                        b.putString("msg", str);
                        msg2.setData(b);
                        h2.sendMessage(msg2);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
h2 = new Handler(){
            @Override
            public void handleMessage(Message msg2) {
                // TODO Auto-generated method stub
                super.handleMessage(msg2);
                Bundle b = msg2.getData();
                String string  = b.getString("msg");
                textView1.setText(string);
            }
        };

你可能感兴趣的:(Android入门与项目实战,嵌入式,android,studio,java,APP,Android)