Wifi局域网的Socket通信(只能一对一的连接的情况)

服务端:

  

import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Zzm_Pc on 2016/12/28.
 */

public class StartingServerUtils {
    private InputStream input;
    private NewServerThread newServerThread;
    private Handler wifiHandler;
    private WifiAcceptThread acceptThread;
    private WifiServerThread serverThread;
    private WifiManager wifiManager;
    private ServerSocket wifiServerSocket;
    private Socket wifiSocket;
    private Context me;

    public StartingServerUtils(Context me, Handler handler) {
        this.me = me;
        this.wifiHandler = handler;
    }

    //accept connect
    private class WifiServerThread extends Thread {
        @Override
        public void run() {
            super.run();
            Log.i("information","WifiServerThread~~");
            try {
                wifiServerSocket = new ServerSocket(1099);
                wifiSocket = wifiServerSocket.accept();
                if (wifiSocket != null) {
                    input = wifiSocket.getInputStream();
                    Log.i("information", "连接成功~~");
                    wifiServerSocket.close();
                    acceptThread.start();
                    newServerThread.start();
                }
            } catch (IOException e) {
                Log.i("information", e.toString());
            }
        }
    }

    //turn string_ip method
    private String getStringIp(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    //accept information thread
    private class WifiAcceptThread extends Thread {
        private boolean is=true;
        @Override
        public void run() {
            super.run();
            Log.i("information","wifiAccept~~");
            if (input != null) {
                while (is) {
                    Log.i("information","读取~~");
                    byte[] bytes = new byte[1024];
                    int length = 0;
                    try {
                        if (input!=null && (length = input.read(bytes)) != -1) {
                            Message msg = new Message();
                            msg.obj = new String(bytes, 0, length);
                            wifiHandler.sendMessage(msg);
                        }
                    } catch (IOException e) {
                        is=false;
                        Log.i("information", "读取异常~~");
                    }
                }
            }

        }
    }

    //开启服务的方法
    public void startServer() {
        wifiManager = (WifiManager) me.getSystemService(Context.WIFI_SERVICE);
        while (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
            Toast.makeText(me, "请开wifi~~", Toast.LENGTH_SHORT).show();
        }
        String ip = getStringIp(wifiManager.getConnectionInfo().getIpAddress());
        //展示ip
        //
        newServerThread = new NewServerThread();
        acceptThread = new WifiAcceptThread();
        serverThread = new WifiServerThread();
        serverThread.start();
    }

    //是否断开连接,断开则重新开启服务
    private class NewServerThread extends Thread {
        private boolean is = true;

        @Override
        public void run() {
            super.run();
            Log.i("information","NewServerThread~~");
            while (is) {
                try {
                    wifiSocket.sendUrgentData(9);
                } catch (IOException e) {
                    Log.i("information", "断开连接了~~");
                    is = false;
                    serverThread.interrupt();
                    acceptThread.interrupt();
                    wifiServerSocket = null;
                    try {
                        wifiSocket.close();
                        input.close();
                    } catch (IOException e1) {
                        Log.i("information", "Socket关闭失败~");
                    }
                    input = null;
                    wifiSocket = null;
                    wifiManager = null;
                    startServer();
                }
            }
            Log.i("information","将会重新开启服务~~");
        }
    }
}

客户端:

public class ConnectServerUtils {
    public static String ip = "192.168.1.89";
    private AppCompatActivity me;
    private WifiManager wifiManager;
    private OutputStream output;
    static Socket wifiSocket;
    public ConnectServerUtils(AppCompatActivity me) {
        this.me = me;
    }

    private class WifiConnectThread extends Thread {

        @Override
        public void run() {
            super.run();
            try {
                wifiSocket = new Socket(ip, 1099);
                output = wifiSocket.getOutputStream();
                if (output != null) {
                    showToast("控制连接成功~~");
                } else {
                    showToast("控制连接失败~请重试!");
                }
            } catch (IOException e) {
                Log.i("information", e.toString());
            }
        }
    }

    private void showToast(final String toastInformation) {
        me.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(me, toastInformation, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public OutputStream startConnectServer() {
        wifiManager = (WifiManager) me.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            Toast.makeText(me, "请开启wifi~~~~", Toast.LENGTH_SHORT).show();
            wifiManager.setWifiEnabled(true);
        }
        Log.i("information", getStringIp(wifiManager.getConnectionInfo().getIpAddress()));
        new WifiConnectThread().start();
        SystemClock.sleep(500);
        return output;
    }

    //turn string_ip method
    private String getStringIp(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }
}

  最后记得要关闭:

@Override
protected void onDestroy() {
    super.onDestroy();
    try {
        ConnectServerUtils.wifiSocket.close();
    } catch (IOException e) {
        Log.i("information", e.toString());
    }
    ConnectServerUtils.wifiSocket = null;
}

不然按返回键的时候,再次连接,服务端会拒绝你的连接,只要加上以上代码就行了。

转载于:https://my.oschina.net/u/2987490/blog/813727

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值