Android socket实现Tcp长连接

这个一个小功能,实现tcp链接,把手机当做服务器跟客户端的综合体,可以不需要外网服务器,只需要手机连接wifi即可

首先贴出Activity的代码跟布局

先上个图片
Android socket实现Tcp长连接_第1张图片

activity_main.xml


<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

   <Button
       android:id="@+id/btn_start_server"
       android:layout_width="match_parent"
       android:layout_marginTop="30dp"
       android:text="启动服务器"
       android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn_start_client"
        android:layout_width="match_parent"
        android:layout_marginTop="30dp"
        android:text="启动客户端"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn_send_client"
        android:layout_width="match_parent"
        android:layout_marginTop="30dp"
        android:text="发送数据(123)给客户端"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn_send_server"
        android:layout_width="match_parent"
        android:layout_marginTop="30dp"
        android:text="发送数据(321)给服务器"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/tv_server"
        android:layout_width="match_parent"
        android:layout_marginTop="30dp"
        android:singleLine="true"
        android:text="服务器收到:"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/tv_client"
        android:layout_width="match_parent"
        android:layout_marginTop="30dp"
        android:singleLine="true"
        android:text="客户端收到:"
        android:layout_height="wrap_content" />

LinearLayout>

MainActivity


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.administrator.dn_data_structure_01.bean.MessageClient;
import com.example.administrator.dn_data_structure_01.bean.MessageServer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class MainActivity extends AppCompatActivity {

    Button btnStartServer;
    Button btnSrartClient;

    Button btnSendToServer;
    Button btnSendToClient;

    TextView tv_server;
    TextView tv_client;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        btnStartServer = findViewById(R.id.btn_start_server);
        btnSrartClient = findViewById(R.id.btn_start_client);
        btnSendToServer = findViewById(R.id.btn_send_server);
        btnSendToClient = findViewById(R.id.btn_send_client);
        tv_server = findViewById(R.id.tv_server);
        tv_client = findViewById(R.id.tv_client);

        btnStartServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开启服务器
               TcpServer.startServer();
            }
        });

        btnSrartClient.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //连接服务器
                TcpClient.startClient( getIPAddress(getApplicationContext()) , 8080);
            }
        });

        btnSendToServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发送数据给服务器
                TcpClient.sendTcpMessage("321");
            }
        });

        btnSendToClient.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发送数据给客户端
                TcpServer.sendTcpMessage("321");
            }
        });

        Log.i("tcp" ,"ip地址:" + getIPAddress(this));

        //注册EventBus
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    //收到客户端的消息
    public void MessageClient(MessageClient messageEvent) {
        tv_client.setText("客户端收到:" +messageEvent.getMsg());
    }

    //收到服务器的消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageServer(MessageServer messageEvent) {
        tv_server.setText("服务器收到:" +messageEvent.getMsg());
    }


    public static String getIPAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}

然后直接上TcpClient类,此类用来开启客户端以及接受服务器消息的代码,然后通过EventBus3.0来实现线程中的通信

TcpClient:

import android.util.Log;

import com.example.administrator.dn_data_structure_01.bean.MessageClient;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class TcpClient {

    public static Socket socket;

    public static void startClient(final String address ,final int port){
        if (address == null){
            return;
        }
        if (socket == null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Log.i("tcp", "启动客户端");
                        socket = new Socket(address, port);
                        Log.i("tcp", "客户端连接成功");
                        PrintWriter pw = new PrintWriter(socket.getOutputStream());

                        InputStream inputStream = socket.getInputStream();

                        byte[] buffer = new byte[1024];
                        int len = -1;
                        while ((len = inputStream.read(buffer)) != -1) {
                            String data = new String(buffer, 0, len);
                            Log.i("tcp", "收到服务器的数据---------------------------------------------:" + data);
                            EventBus.getDefault().post(new MessageClient(data));
                        }
                        Log.i("tcp", "客户端断开连接");
                        pw.close();

                    } catch (Exception EE) {
                        EE.printStackTrace();
                        Log.i("tcp", "客户端无法连接服务器");

                    }finally {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        socket = null;
                    }
                }
            }).start();
        }
    }

    public static void sendTcpMessage(final String msg){
        if (socket != null && socket.isConnected()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        socket.getOutputStream().write(msg.getBytes());
                        socket.getOutputStream().flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}

接下来是服务器的类。用自己手机即当服务器又当客户端。
TcpServer:


import android.util.Log;

import com.example.administrator.dn_data_structure_01.bean.MessageServer;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
    private static ServerSocket serverSocket;
    private static Socket socket;

    public static void startServer(){
        if (serverSocket == null){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        serverSocket = new ServerSocket(8080);
                        Log.i("tcp" , "服务器等待连接中");
                        socket = serverSocket.accept();
                        Log.i("tcp" , "客户端连接上来了");
                        InputStream inputStream = socket.getInputStream();
                        byte[] buffer = new byte[1024];
                        int len = -1;
                        while ((len = inputStream.read(buffer)) != -1) {
                            String data = new String(buffer, 0, len);
                            Log.i("tcp" , "收到客户端的数据-----------------------------:" + data);
                            EventBus.getDefault().post(new MessageServer(data));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();

                    }finally {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        try {
                            serverSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        socket = null;
                        serverSocket = null;
                    }
                }
            }).start();
        }
    }

    public static void sendTcpMessage(final String msg){
        if (socket != null && socket.isConnected()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        socket.getOutputStream().write(msg.getBytes());
                        socket.getOutputStream().flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}



大功告成了,功能还是比较简单的。

最后再上个demo

你可能感兴趣的:(android开发)