andriod studio tcp client通讯的实现

主要参考了以下链接

http://blog.csdn.net/shankezh/article/details/70763579

对于重连的出错处理好像有点问题。

1 我的布局

xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.lenovo.chentcpclient.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="26dp"
        android:layout_height="29dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="4dp"
        android:layout_marginTop="8dp"
        android:autoText="true"
        android:text="IP:"
        android:textSize="18dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.036" />

    <EditText
        android:id="@+id/editText_ip"
        android:layout_width="158dp"
        android:layout_height="51dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="192.168.1.102"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.018" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="45dp"
        android:layout_height="32dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="12dp"
        android:layout_marginTop="8dp"
        android:text="Port:"
        android:textSize="18dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/editText_ip"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.036" />

    <EditText
        android:id="@+id/editText_port"
        android:layout_width="67dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="8002"
        app:layout_constraintBottom_toTopOf="@+id/button_clrecv"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.16"
        app:layout_constraintStart_toEndOf="@+id/textView2"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.586" />

    <Button
        android:id="@+id/button_connect"
        android:layout_width="67dp"
        android:layout_height="40dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="4dp"
        android:layout_marginTop="8dp"
        android:text="连接"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.158" />

    <Button
        android:id="@+id/button_close"
        android:layout_width="70dp"
        android:layout_height="40dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:text="断开"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/button_clrecv"
        app:layout_constraintStart_toEndOf="@+id/button_connect"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.158" />

    <Button
        android:id="@+id/button_clrecv"
        android:layout_width="95dp"
        android:layout_height="40dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginTop="8dp"
        android:text="清除接收区"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/button_clsend"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.158" />

    <Button
        android:id="@+id/button_clsend"
        android:layout_width="94dp"
        android:layout_height="38dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="4dp"
        android:layout_marginTop="8dp"
        android:text="清除发送区"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.157" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="20dp"
        android:text="接收区"
        app:layout_constraintBottom_toTopOf="@+id/editText_receive"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.058"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_connect" />

    <EditText
        android:id="@+id/editText_receive"
        android:layout_width="350dp"
        android:layout_height="109dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="160dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="send"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="发送区"
        app:layout_constraintBottom_toTopOf="@+id/editText_send"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.067"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_receive"
        app:layout_constraintVertical_bias="0.0" />

    <EditText
        android:id="@+id/editText_send"
        android:layout_width="352dp"
        android:layout_height="135dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="recv"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_receive"
        app:layout_constraintVertical_bias="0.307" />

    <EditText
        android:id="@+id/editText_sendnow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="hello"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_send"
        app:layout_constraintVertical_bias="0.111" />

    <Button
        android:id="@+id/button_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="发送"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.326"
        app:layout_constraintStart_toEndOf="@+id/editText_sendnow"
        app:layout_constraintTop_toBottomOf="@+id/editText_send"
        app:layout_constraintVertical_bias="0.0" />
android.support.constraint.ConstraintLayout>

2 tcpclient代码

package com.example.lenovo.chentcpclient;

import android.content.Intent;
import android.util.Log;

import java.io.BufferedReader;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import com.example.lenovo.chentcpclient.MainActivity;
/**
 * Created by Lenovo on 2018/2/22.
 */

public class TcpClient implements Runnable{
    private String TAG = "TcpClient";
    private String  serverIP = "192.168.88.141";
    private int serverPort = 1234;
    private PrintWriter pw;
    private InputStream is;
    private DataInputStream dis;
    private boolean isRun = true;
    private Socket socket = null;
    byte buff[]  = new byte[4096];
    private String rcvMsg;
    private int rcvLen;



    public TcpClient(String ip , int port){
        this.serverIP = ip;
        this.serverPort = port;
    }

    public void closeSelf(){
        isRun = false;
    }

    public void send(String msg){
        pw.println(msg);
        pw.flush();
    }

    @Override
    public void run() {
        try {
            socket = new Socket(serverIP,serverPort);
            socket.setSoTimeout(5000);
            pw = new PrintWriter(socket.getOutputStream(),true);
            is = socket.getInputStream();
            dis = new DataInputStream(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (isRun){
            try {
                rcvLen = dis.read(buff);
                rcvMsg = new String(buff,0,rcvLen,"utf-8");
                Log.i(TAG, "run: 收到消息:"+ rcvMsg);
                Intent intent =new Intent();
                intent.setAction("tcpClientReceiver");
                intent.putExtra("tcpClientReceiver",rcvMsg);
                MainActivity.context.sendBroadcast(intent);//将消息发送给主界面
                if (rcvMsg.equals("QuitClient")){   //服务器要求客户端结束
                    isRun = false;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        try {
            pw.close();
            is.close();
            dis.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

3 mainactivity的代码

package com.example.lenovo.chentcpclient;

import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.lang.ref.WeakReference;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Handler;
import com.example.lenovo.chentcpclient.TcpClient;

public class MainActivity extends AppCompatActivity {
    private String TAG = "FuncTcpClient";
    @SuppressLint("StaticFieldLeak")
    public static Context context ;
    private Button btconnect = null;
    private Button btclose= null;
    private Button btclearreceivetext = null;
    private Button btclearsendtext = null;
    private Button btsend = null;

    private TextView textip = null;
    private TextView textport = null;
    private TextView textreceive = null;
    private TextView textsend = null;
    private TextView textsendnow = null;

    private static TcpClient tcpClient = null;
    private final MyHandler myHandler = new MyHandler(this);
    private MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
    ExecutorService exec = Executors.newCachedThreadPool();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        btconnect = (Button) findViewById(R.id.button_connect);
        btclose = (Button) findViewById(R.id.button_close);
        btclearreceivetext = (Button) findViewById(R.id.button_clrecv);
        btclearsendtext = (Button) findViewById(R.id.button_clsend);
        btsend = (Button) findViewById(R.id.button_send);


        textip = (TextView) findViewById(R.id.editText_ip);
        textport = (TextView) findViewById(R.id.editText_port);
        textreceive = (TextView) findViewById(R.id.editText_receive);
        textsend = (TextView) findViewById(R.id.editText_send);
        textsendnow = (TextView) findViewById(R.id.editText_sendnow);


        btconnect.setOnClickListener(listener);
        btclose.setOnClickListener(listener);
        btclearreceivetext.setOnClickListener(listener);
        btclearsendtext.setOnClickListener(listener);
        btsend.setOnClickListener(listener);
        bindReceiver();
        Ini();
    }
    private View.OnClickListener listener = new View.OnClickListener() {
        public void onClick(View v) {
            if (v == btconnect)
            {
                Log.i(TAG, "onClick: 开始");
                btconnect.setEnabled(false);
                btclose.setEnabled(true);
                btsend.setEnabled(true);
                tcpClient = new TcpClient(textip.getText().toString(),getPort(textport.getText().toString()));
                exec.execute(tcpClient);

            }
            if (v == btclose)
            {
                tcpClient.closeSelf();
                btconnect.setEnabled(true);
                btclose.setEnabled(false);
                btsend.setEnabled(false);
            }
            if (v == btclearreceivetext)
            {
                textreceive.setText("");
            }
            if (v == btclearsendtext)
            {
                textsend.setText("");
            }
            if (v == btsend)
            {
                Message message = Message.obtain();
                message.what = 2;
                message.obj = textsendnow.getText().toString();
                myHandler.sendMessage(message);
                exec.execute(new Runnable() {
                    @Override
                    public void run() {
                        tcpClient.send(textsendnow.getText().toString());
                    }
                });
            }
        }
    };
    private class MyHandler extends android.os.Handler{
        private WeakReference mActivity;

        MyHandler(MainActivity activity){
            mActivity = new WeakReference(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (mActivity != null){
                switch (msg.what){
                    case 1:
                        textreceive.append(msg.obj.toString());
                        break;
                    case 2:
                        textsend.append(msg.obj.toString());
                        break;
                }
            }
        }
    }

    private class MyBroadcastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String mAction = intent.getAction();
            switch (mAction){
                case "tcpClientReceiver":
                    String msg = intent.getStringExtra("tcpClientReceiver");
                    Message message = Message.obtain();
                    message.what = 1;
                    message.obj = msg;
                    myHandler.sendMessage(message);
                    break;
            }
        }
    }


    private int getPort(String msg){
        if (msg.equals("")){
            msg = "1234";
        }
        return Integer.parseInt(msg);
    }


    private void bindReceiver(){
        IntentFilter intentFilter = new IntentFilter("tcpClientReceiver");
        registerReceiver(myBroadcastReceiver,intentFilter);
    }
    private void Ini(){
        btclose.setEnabled(false);
        btsend.setEnabled(false);
    }
}

你可能感兴趣的:(安卓studio)