Android Wifi热点 数据传输Socket 通信

首先,描述下功能,两个手机,其中一个手机开热点,另外一个手机连接热点,2个手机间数据通信(不需要流量)。简述一下原理:开热点的手机相当于路由器,连接的手机作为客户端,获取路由器的IP建立Socket 连接,开始双方通信。


一、服务器端:

开热点的作为服务器端

初始化数据:

    public static final int DEVICE_CONNECTING = 1;//有设备正在连接热点
    public static final int DEVICE_CONNECTED  = 2;//有设备连上热点
    public static final int SEND_MSG_SUCCSEE  = 3;//发送消息成功
    public static final int SEND_MSG_ERROR    = 4;//发送消息失败
    public static final int GET_MSG           = 6;//获取新消息
    private TextView      text_state;
    private WifiManager   wifiManager;
    /**
     * 连接线程
     */
    private ConnectThread connectThread;


    /**
     * 监听线程
     */
    private ListenerThread listenerThread;
    /**
     * 热点名称
     */
    private static final String WIFI_HOTSPOT_SSID = "TEST";
    /**
     * 端口号
     */
    private static final int    PORT              = 54321;

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

        findViewById(R.id.create_wifi).setOnClickListener(this);
        findViewById(R.id.close_wifi).setOnClickListener(this);
        findViewById(R.id.send).setOnClickListener(this);
        text_state = (TextView) findViewById(R.id.receive);


        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        /**
         * 先开启监听线程,在开启连接
         */
        listenerThread = new ListenerThread(PORT, handler);
        listenerThread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //        开启连接线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.i("ip", "getWifiApIpAddress()" + getWifiApIpAddress());
                    //本地路由开启通信
                    String ip = getWifiApIpAddress();
                    if (ip != null) {
                    } else {
                        ip = "192.168.43.1";
                    }
                    Socket socket = new Socket(ip, PORT);
                    connectThread = new ConnectThread(MainActivity.this, socket, handler);
                    connectThread.start();

                } catch (IOException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            text_state.setText("创建通信失败");
                        }
                    });

                }
            }
        }).start();


    }

创建wifi 热点,之后开启Socket 监听线程

 /**
     * 创建Wifi热点
     */
    private void createWifiHotspot() {
        if (wifiManager.isWifiEnabled()) {
            //如果wifi处于打开状态,则关闭wifi,
            wifiManager.setWifiEnabled(false);
        }
        final WifiConfiguration config = new WifiConfiguration();
        config.SSID = WIFI_HOTSPOT_SSID;
        config.preSharedKey = "123456789";
        config.hiddenSSID = false;
        config.allowedAuthAlgorithms
                .set(WifiConfiguration.AuthAlgorithm.OPEN);//开放系统认证
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        config.allowedPairwiseCiphers
                .set(WifiConfiguration.PairwiseCipher.TKIP);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        config.allowedPairwiseCiphers
                .set(WifiConfiguration.PairwiseCipher.CCMP);
        config.status = WifiConfiguration.Status.ENABLED;
        //通过反射调用设置热点

        //192.168.43.59
        //        Log.i("ip", "getWifiApIpAddress()" + getWifiApIpAddress() +
        //                "\n");
        try {
            Method method = wifiManager.getClass().getMethod(
                    "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
            boolean enable = (Boolean) method.invoke(wifiManager, config, true);
            if (enable) {
                text_state.setText("热点已开启 SSID:" + WIFI_HOTSPOT_SSID + " password:123456789");


                //        开启连接线程
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Log.i("ip", "getWifiApIpAddress()" + getWifiApIpAddress()
                            );
                            String ip = getWifiApIpAddress();
                            if (ip != null) {
                            } else {
                                //一般Android手机默认路由是
                                ip = "192.168.43.1";
                            }
                            //本地路由开启通信
                            Socket socket = new Socket(ip, PORT);
                            connectThread = new ConnectThread(MainActivity.this, socket, handler);
                            connectThread.start();


                        } catch (IOException e) {
                            e.printStackTrace();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    text_state.setText("创建通信失败");
                                }
                            });

                        }
                    }
                }).start();
                Thread.sleep(1000);

                //                listenerThread = new ListenerThread(PORT, handler);
                //                listenerThread.start();
            } else {
                text_state.setText("创建热点失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            text_state.setText("创建热点失败");
        }
    }

服务器端获取本地路由:

   public String getWifiApIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                if (intf.getName().contains("wlan")) {
                    for (Enumeration<InetAddress> enumIpAddr = intf
                            .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()
                                && (inetAddress.getAddress().length == 4)) {
                            Log.d("Main", inetAddress.getHostAddress());
                            return inetAddress.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("Main", ex.toString());
        }
        return null;
    }

关闭热点

 /**
     * 关闭WiFi热点
     */
    public void closeWifiHotspot() {
        try {
            Method method = wifiManager.getClass().getMethod("getWifiApConfiguration");
            method.setAccessible(true);
            WifiConfiguration config = (WifiConfiguration) method.invoke(wifiManager);
            Method method2 = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            method2.invoke(wifiManager, config, false);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        text_state.setText("热点已关闭");
    }

ListenerThread 监听线程

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.example.syhuang.wifiserver.MainActivity;

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

/**
 * 监听线程
 * Created by syh on 2018/4/3
 */
public class ListenerThread extends Thread {

    private ServerSocket serverSocket = null;
    private Handler handler;
    private int     port;
    private Socket  socket;

    public ListenerThread(int port, Handler handler) {
        setName("ListenerThread");
        this.port = port;
        this.handler = handler;
        try {
            serverSocket = new ServerSocket(port);//监听本机的12345端口
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void run() {
        while (true) {
            try {
                Log.i("ListennerThread", "阻塞");
                //阻塞,等待设备连接
                if (serverSocket != null)
                    socket = serverSocket.accept();
                Message message = Message.obtain();
                message.what = MainActivity.DEVICE_CONNECTING;
                handler.sendMessage(message);
            } catch (IOException e) {
                Log.i("ListennerThread", "error:" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    public Socket getSocket() {
        return socket;
    }
}

ConnectThread 连接线程

package com.example.syhuang.wifiserver.thread;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.example.syhuang.wifiserver.MainActivity;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.text.DecimalFormat;

/**
 * 连接线程
 * Created by syhuang on 2018/4/3
 */
public class ConnectThread extends Thread {

    private final Socket       socket;
    private       Handler      handler;
    private       InputStream  inputStream;
    private       OutputStream outputStream;
    Context context;

    public ConnectThread(Context context, Socket socket, Handler handler) {
        setName("ConnectThread");
        Log.i("ConnectThread", "ConnectThread");
        this.socket = socket;
        this.handler = handler;
        this.context = context;
    }

    @Override
    public void run() {
/*        if(activeConnect){
//            socket.c
        }*/
        if (socket == null) {
            return;
        }
        handler.sendEmptyMessage(MainActivity.DEVICE_CONNECTED);
        try {
            //获取数据流
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();

            byte[] buffer = new byte[1024];
            int bytes;
            while (true) {

                //读取数据
                bytes = inputStream.read(buffer);
                if (bytes > 0) {
                    final byte[] data = new byte[bytes];
                    System.arraycopy(buffer, 0, data, 0, bytes);

                    Message message = Message.obtain();
                    message.what = MainActivity.GET_MSG;
                    Bundle bundle = new Bundle();
                    bundle.putString("MSG", new String(data));
                    message.setData(bundle);
                    handler.sendMessage(message);
                }
                //                DataInputStream dis = null;
                //                FileOutputStream fos = null;
                //                try {
                //                    dis = new DataInputStream(inputStream);
                //
                //                    // 文件名和长度
                //                    String fileName = dis.readUTF();
                //                    if (!fileName.equals("")) {
                //                        long fileLength = dis.readLong();
                //                        Log.i("ConnectThread", "======== 文件接收 [File Name:" + fileName + "] " +
                //                                "[Size:" + getFormatFileSize(fileLength) + "] ========");
                //                        File directory = new File(Environment.getExternalStorageDirectory() + "/");
                //                        if (!directory.exists()) {
                //                            directory.mkdir();
                //                        } else {
                //                        }
                //                        File file = new File(directory.getAbsolutePath() + File.separatorChar + fileName);
                //                        fos = new FileOutputStream(file);
                //
                //                        // 开始接收文件
                //                        byte[] bytesA = new byte[1024];
                //                        int length = 0;
                //                        int progress = 0;
                //                        while ((length = dis.read(bytesA, 0, bytesA.length)) != -1) {
                //                            Log.i("ConnectThread", length + "...");
                //                            fos.write(bytesA, 0, length);
                //                            fos.flush();
                //                            progress += length;
                //                            Log.i("ConnectThread", "| " + (100 * progress / file.length()) + "% |");
                //                        }
                //                        Log.i("ConnectThread", "文件传输完成");
                //
                //                        Message message = Message.obtain();
                //                        message.what = MainActivity.GET_MSG;
                //                        Bundle bundle = new Bundle();
                //                        bundle.putString("MSG", new String("接收到文件:" + file.getAbsolutePath()));
                //                        message.setData(bundle);
                //                        handler.sendMessage(message);
                //                    } else {
                //                        //读取数据
                //                        bytes = inputStream.read(buffer);
                //                        if (bytes > 0) {
                //                            final byte[] data = new byte[bytes];
                //                            System.arraycopy(buffer, 0, data, 0, bytes);
                //
                //
                //                            Message message = Message.obtain();
                //                            message.what = MainActivity.GET_MSG;
                //                            Bundle bundle = new Bundle();
                //                            bundle.putString("MSG", new String(data));
                //                            message.setData(bundle);
                //                            handler.sendMessage(message);
                //
                //                            Log.i("ConnectThread", "读取到数据:" + new String(data));
                //                        }
                //                    }


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

    /**
     * 格式化文件大小
     *
     * @param length
     * @return
     */
    private String getFormatFileSize(long length) {
        DecimalFormat df = new DecimalFormat("#0.0");
        double size = ((double) length) / (1 << 30);
        if (size >= 1) {
            return df.format(size) + "GB";
        }
        size = ((double) length) / (1 << 20);
        if (size >= 1) {
            return df.format(size) + "MB";
        }
        size = ((double) length) / (1 << 10);
        if (size >= 1) {
            return df.format(size) + "KB";
        }
        return length + "B";
    }

    public static boolean copyFile(InputStream inputStream, OutputStream out) {
        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                out.write(buf, 0, len);

            }
            out.close();
            //            inputStream.close();
        } catch (IOException e) {

            return false;
        }
        return true;
    }

    /**
     * 发送数据
     */
    public void sendData(String msg) {
        Log.i("ConnectThread", "发送数据:" + (outputStream == null));
        if (outputStream != null) {
            try {
                outputStream.write(msg.getBytes());
                Log.i("ConnectThread", "发送消息:" + msg);
                Message message = Message.obtain();
                message.what = MainActivity.SEND_MSG_SUCCSEE;
                Bundle bundle = new Bundle();
                bundle.putString("MSG", new String(msg));
                message.setData(bundle);
                handler.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
                Message message = Message.obtain();
                message.what = MainActivity.SEND_MSG_ERROR;
                Bundle bundle = new Bundle();
                bundle.putString("MSG", new String(msg));
                message.setData(bundle);
                handler.sendMessage(message);
            }
        }
    }

}

二、客户端

客户端连接到热点,代码差不多,初始化数据部分顺序不一样,先开启连接线程,在开启监听线程,获取路由器IP 地址有差别。其他基本一样。

wifi获取 已连接网络路由 路由ip地址

    /**
     * wifi获取 已连接网络路由  路由ip地址
     * @param context
     * @return
     */
    private static String getWifiRouteIPAddress(Context context) {
        WifiManager wifi_service = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        DhcpInfo dhcpInfo = wifi_service.getDhcpInfo();
        //        WifiInfo wifiinfo = wifi_service.getConnectionInfo();
        //        System.out.println("Wifi info----->" + wifiinfo.getIpAddress());
        //        System.out.println("DHCP info gateway----->" + Formatter.formatIpAddress(dhcpInfo.gateway));
        //        System.out.println("DHCP info netmask----->" + Formatter.formatIpAddress(dhcpInfo.netmask));
        //DhcpInfo中的ipAddress是一个int型的变量,通过Formatter将其转化为字符串IP地址
        String routeIp = Formatter.formatIpAddress(dhcpInfo.gateway);
        Log.i("route ip", "wifi route ip:" + routeIp);

        return routeIp;
    }

初始化

 public static final int DEVICE_CONNECTING = 1;//有设备正在连接热点
    public static final int DEVICE_CONNECTED  = 2;//有设备连上热点
    public static final int SEND_MSG_SUCCSEE  = 3;//发送消息成功
    public static final int SEND_MSG_ERROR    = 4;//发送消息失败
    public static final int GET_MSG           = 6;//获取新消息

    private TextView      text_state;
    /**
     * 连接线程
     */
    private ConnectThread connectThread;


    /**
     * 监听线程
     */
    private ListenerThread listenerThread;

    /**
     * 热点名称
     */
    private static final String WIFI_HOTSPOT_SSID = "TEST";
    /**
     * 端口号
     */
    private static final int    PORT              = 54321;
    private WifiManager wifiManager;

    private TextView status_init;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.send).setOnClickListener(this);
        findViewById(R.id.connect).setOnClickListener(this);
        findViewById(R.id.fileButton).setOnClickListener(this);
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        //检查Wifi状态
        if (!wifiManager.isWifiEnabled())
            wifiManager.setWifiEnabled(true);
        text_state = (TextView) findViewById(R.id.status_info);
        status_init = (TextView) findViewById(R.id.status_init);


        status_init.setText("已连接到:" + wifiManager.getConnectionInfo().getSSID() +
                "\nIP:" + getIp()
                + "\n路由:" + getWifiRouteIPAddress(MainActivity.this));

        //        initBroadcastReceiver();
        //        开启连接线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Socket socket = new Socket(getWifiRouteIPAddress(MainActivity.this), PORT);
                    connectThread = new ConnectThread(socket, handler);
                    connectThread.start();
                } catch (IOException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            text_state.setText("通信连接失败");
                        }
                    });

                }
            }
        }).start();


        listenerThread = new ListenerThread(PORT, handler);
        listenerThread.start();
    }

服务器和客户端Handler处理一样

  private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DEVICE_CONNECTING:
                    connectThread = new ConnectThread(listenerThread.getSocket(), handler);
                    connectThread.start();
                    break;
                case DEVICE_CONNECTED:
                    text_state.setText("设备连接成功");
                    break;
                case SEND_MSG_SUCCSEE:
                    text_state.setText("发送消息成功:" + msg.getData().getString("MSG"));
                    break;
                case SEND_MSG_ERROR:
                    text_state.setText("发送消息失败:" + msg.getData().getString("MSG"));
                    break;
                case GET_MSG:
                    text_state.setText("收到消息:" + msg.getData().getString("MSG"));
                    break;
            }
        }
    };


源码传送门

参考文章:

Android 连接Wifi和创建Wifi热点 demo - CSDN博客
Android WiFi开发 (一)扫描、连接、信息 - CSDN博客
Android/安卓开发之WIFI的基本应用 - CSDN博客
Android设备之间通过Wifi通信 - sowhat4999 - 博客园
Android WiFi开发教程(三)——WiFi热点数据传输 - CSDN博客
【Android】Android手机通过wifi进行数据传输 - CSDN博客
android wifi 点对点传输 - 简书
android WIFI Socket 文件传输 - Android移动开发技术文章_手机开发 - 红黑联盟
Android 实现无网络传输文件用户5207283611新浪博客
wifi direct—深入理解Wi-Fi P2P - CSDN博客
(高效开发)Android手机间使用socket进行文件互传实例 - CSDN博客
Android仿茄子快传-实现面对面快传功能 - CSDN博客
安卓手机wifi面对面快传的实现 - CSDN博客

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,542评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,596评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,021评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,682评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,792评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,985评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,107评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,845评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,299评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,612评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,747评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,441评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,072评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,828评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,069评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,545评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,658评论 2 350

推荐阅读更多精彩内容