andriod studio TCP server

转载于

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


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_start"
        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_start"
        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_start" />

    <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 TcpServer文件

package com.example.lenovo.chentcpserver;
import android.content.Intent;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by Lenovo on 2018/2/22.
 */
import com.example.lenovo.chentcpserver.MainActivity;

public class TcpServer implements Runnable{
    private String TAG = "TcpServer";
    private int port = 1234;
    private boolean isListen = true;   //线程监听标志位
    public ArrayList SST = new ArrayList();
    public TcpServer(int port){
        this.port = port;
    }

    //更改监听标志位
    public void setIsListen(boolean b){
        isListen = b;
    }

    public void closeSelf(){
        isListen = false;
        for (ServerSocketThread s : SST){
            s.isRun = false;
        }
        SST.clear();
    }

    private Socket getSocket(ServerSocket serverSocket){
        try {
            return serverSocket.accept();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i(TAG, "run: 监听超时");
            return null;
        }
    }

    @Override
    public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            serverSocket.setSoTimeout(5000);
            while (isListen){
                Log.i(TAG, "run: 开始监听...");

                Socket socket = getSocket(serverSocket);
                if (socket != null){
                    new ServerSocketThread(socket);
                }
            }

            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public class ServerSocketThread extends Thread{
        Socket socket = null;
        private PrintWriter pw;
        private InputStream is = null;
        private OutputStream os = null;
        private String ip = null;
        private boolean isRun = true;

        ServerSocketThread(Socket socket){
            this.socket = socket;
            ip = socket.getInetAddress().toString();
            Log.i(TAG, "ServerSocketThread:检测到新的客户端联入,ip:" + ip);

            try {
                socket.setSoTimeout(5000);
                os = socket.getOutputStream();
                is = socket.getInputStream();
                pw = new PrintWriter(os,true);
                start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void send(String msg){
            pw.println(msg);
            pw.flush(); //强制送出数据
        }

        @Override
        public void run() {
            byte buff[]  = new byte[4096];
            String rcvMsg;
            int rcvLen;
            SST.add(this);
            while (isRun && !socket.isClosed() && !socket.isInputShutdown()){
                try {
                    if ((rcvLen = is.read(buff)) != -1 ){
                        rcvMsg = new String(buff,0,rcvLen);
                        Log.i(TAG, "run:收到消息: " + rcvMsg);
                        Intent intent =new Intent();
                        intent.setAction("tcpServerReceiver");
                        intent.putExtra("tcpServerReceiver",rcvMsg);
                        MainActivity.context.sendBroadcast(intent);//将消息发送给主界面
                        if (rcvMsg.equals("QuitServer")){
                            isRun = false;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                socket.close();
                SST.clear();
                Log.i(TAG, "run: 断开连接");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

3 mianactivity文件

package com.example.lenovo.chentcpserver;

import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

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.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.example.lenovo.chentcpserver.TcpServer;

public class MainActivity extends AppCompatActivity {
    private static TcpServer tcpServer = null;
    private final MyHandler myHandler = new MyHandler(this);
    private MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
    @SuppressLint("StaticFieldLeak")
    public static Context context;
    ExecutorService exec = Executors.newCachedThreadPool();

    private Button btstart = 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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        btstart = (Button) findViewById(R.id.button_start);
        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);


        btstart.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 == btstart)
            {
                Log.i("A", "onClick: 开始");
                btstart.setEnabled(false);
                btclose.setEnabled(true);
                btsend.setEnabled(true);
                 tcpServer = new TcpServer(getHost(textport.getText().toString()));
                 exec.execute(tcpServer);


            }
            if (v == btclose)
            {
                tcpServer.closeSelf();
                btstart.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() {
                           tcpServer.SST.get(0).send(textsendnow.getText().toString());
                                    }
                  });

            }
        }
    };
    private class MyHandler extends android.os.Handler{
         private final WeakReference mActivity;
         MyHandler(MainActivity activity){
                         mActivity = new WeakReference(activity);
                     }


           @Override
         public void handleMessage(Message msg) {
               MainActivity activity = mActivity.get();
                       if (activity!= 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 "tcpServerReceiver":
                                        String msg = intent.getStringExtra("tcpServerReceiver");
                                         Message message = Message.obtain();
                                         message.what = 1;
                                         message.obj = msg;
                                        myHandler.sendMessage(message);
                                         break;
                             }
                     }
    }


             private void bindReceiver(){
                 IntentFilter intentFilter = new IntentFilter("tcpServerReceiver");
                 registerReceiver(myBroadcastReceiver,intentFilter);
             }
            private int getHost(String msg){
             if (msg.equals("")){
                        msg = "1234";
                    }
                return Integer.parseInt(msg);
            }
             private void ini(){
                 btclose.setEnabled(false);
                 btsend.setEnabled(false);
                 textip.setText(getHostIP());
            }
    /**
           * 获取ip地址
          * @return
          */
     public String getHostIP() {


                String hostIp = null;
               try {
                        Enumeration nis = NetworkInterface.getNetworkInterfaces();
                         InetAddress ia = null;
                        while (nis.hasMoreElements()) {
                                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                                Enumeration ias = ni.getInetAddresses();
                                while (ias.hasMoreElements()) {
                                        ia = ias.nextElement();
                                        if (ia instanceof Inet6Address) {
                                                continue;// skip ipv6
                                             }
                                        String ip = ia.getHostAddress();
                                        if (!"127.0.0.1".equals(ip)) {
                                                hostIp = ia.getHostAddress();
                                                break;
                                            }
                                     }
                             }
                    } catch (SocketException e) {
                         Log.i("FuncTcpServer", "SocketException");
                        e.printStackTrace();
                     }
                 return hostIp;


             }



}

4 当然,权限不要忘记了

<uses-permission android:name="android.permission.INTERNET"/>

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