设为首页 收藏本站
查看: 687|回复: 0

[经验分享] android wifi 热点、socket通讯

[复制链接]

尚未签到

发表于 2015-9-30 12:25:01 | 显示全部楼层 |阅读模式
  WiFi管理工具类



package com.wyf.app.common;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
public class WifiManageUtils
{
private static WifiManager wifiManager;
private static WifiInfo wifiInfo;
private static List<ScanResult> wifiScanlist;
private static List<WifiConfiguration> wifiConfigurationlist;
private static DhcpInfo wifiDhcpInfo;
public WifiManageUtils(Context context)
{
// 取得WifiManager对象
wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
}
public WifiInfo getWifiConnectInfo()
{
wifiInfo = wifiManager.getConnectionInfo();
return wifiInfo;
}
public List<ScanResult> getScanResult()
{
wifiScanlist = wifiManager.getScanResults();
return wifiScanlist;
}
public List<WifiConfiguration> getConfiguration()
{
wifiConfigurationlist = wifiManager.getConfiguredNetworks();
return wifiConfigurationlist;
}
public DhcpInfo getDhcpInfo()
{
wifiDhcpInfo = wifiManager.getDhcpInfo();
return wifiDhcpInfo;
}
/**
* 开启热点作为服务端的配置
*
* @param ssid
* @param passwd
* @param type
* @return
*/
public WifiConfiguration getCustomeWifiConfiguration(String ssid,
String passwd, int type)
{
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = ssid;
if (type == 1) // NOPASS
    {
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (type == 2) // WEP
    {
config.hiddenSSID = true;
config.wepKeys[0] = passwd;
config.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.WEP104);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (type == 3) // WPA
    {
config.preSharedKey = passwd;
config.hiddenSSID = true;
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.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
config.status = WifiConfiguration.Status.ENABLED;
}
if (type == 4) // WPA2psk test
    {
config.preSharedKey = passwd;
config.hiddenSSID = true;
config.status = WifiConfiguration.Status.ENABLED;
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
}
return config;
}
/**
* 客户端添加配置,作为连接认证配置
* ssid、passwd 配置前后必须加上双引号“
* @param ssid
* @param passwd
* @param type
* @return
*/
public WifiConfiguration getCustomeWifiClientConfiguration(String ssid,
String passwd, int type)
{
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
//双引号必须
config.SSID = "\"" + ssid + "\"";
if (type == 1) // WIFICIPHER_NOPASS
    {
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (type == 2) // WIFICIPHER_WEP
    {
config.hiddenSSID = true;
config.wepKeys[0] = "\"" + passwd + "\"";
config.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.WEP104);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (type == 3) // WIFICIPHER_WPA
    {
config.preSharedKey = "\"" + passwd + "\"";
config.hiddenSSID = true;
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.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
config.status = WifiConfiguration.Status.ENABLED;
}
if (type == 4) // WPA2psk test
    {
config.preSharedKey = "\"" + passwd + "\"";
config.hiddenSSID = true;
config.status = WifiConfiguration.Status.ENABLED;
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
}
return config;
}
public Boolean stratWifiAp(String ssid, String psd, int type)
{
Method method1 = null;
try
{
method1 = wifiManager.getClass().getMethod("setWifiApEnabled",
WifiConfiguration.class, boolean.class);
WifiConfiguration netConfig = getCustomeWifiConfiguration(ssid,
psd, type);
method1.invoke(wifiManager, netConfig, true);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
public void closeWifiAp()
{
if (isWifiApEnabled())
{
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();
}
}
}
public boolean isWifiApEnabled()
{
try
{
Method method = wifiManager.getClass().getMethod("isWifiApEnabled");
method.setAccessible(true);
return (Boolean) method.invoke(wifiManager);
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
}
  开启热点服务端部分代码



    public void startWifiHot()
{
btnServer.setEnabled(false);
if (wifiManager.isWifiEnabled())
{
wifiManager.setWifiEnabled(false);
}
Boolean b = wifimanageutils.stratWifiAp(mSSID, mPasswd,3);
if (b)
{
serverThread = new WifiServerThread(context, testh);
Toast.makeText(context, "server 端启动", 3000).show();
serverThread.start();
}
else
{
btnServer.setEnabled(true);
Toast.makeText(context, "server 端失败,请重试", 3000).show();
}
}
  WifiServerThread服务端线程



public class WifiServerThread extends Thread
{
public ServerSocket mserverSocket;
public Socket socket;
public Context context;
public static final int SERVERPORT = 8191;
public Boolean isrun = true;
public Handler handler;
public WifiServerThread(Context context, Handler handler)
{
this.context = context;
this.handler = handler;
}
public void run()
{
try
{
mserverSocket = new ServerSocket(SERVERPORT);
while (isrun)
{
socket = mserverSocket.accept();
new Thread(new Runnable()
{
@Override
public void run()
{
byte[] buffer = new byte[1024];
int bytes;
InputStream mmInStream = null;
try
{
mmInStream = socket.getInputStream();
}
catch (IOException e1)
{
e1.printStackTrace();
}
System.out.println("server");
try
{
InputStream in = socket.getInputStream();
OutputStream os = socket.getOutputStream();
byte[] data = new byte[1024];
while (in.available() <= 0)
;// 同步
int len = in.read(data);
String[] str = new String(data, 0, len, "utf-8")
.split(";");
String path = Environment
.getExternalStorageDirectory()
.getAbsolutePath()
+ "/CHFS/000000000000" + "/";
if (len != -1)
{
path += "socket_" + str[0];// str[0]是文件名加类型
                }
handler.obtainMessage(10, (Object) str[0])
.sendToTarget();
System.out.println(path);
os.write("start".getBytes());
os.flush();
File file = new File(path);
DataOutputStream out = new DataOutputStream(
new FileOutputStream(file));
System.out.println("开始接收.....");
int countSize = 0;
while ((len = in.read(data)) != -1)
{
out.write(data, 0, len);
countSize += len;
}
os.close();
out.flush();
out.close();
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
System.out.println("关闭....");
}
catch (Exception e)
{
e.printStackTrace();
}
handler.obtainMessage(10, (Object) "接受 完成")
.sendToTarget();
}
}
}).start();
}
if (mserverSocket != null)
{
try
{
mserverSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
  开启客户端部分代码



btnClient.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
WifiConfiguration netConfig = wifimanageutils
.getCustomeWifiClientConfiguration(mSSID, mPasswd,3);
int wcgID = wifiManager.addNetwork(netConfig);
boolean b = wifiManager.enableNetwork(wcgID, true);
Boolean iptoready = false;
if (!b)
{
Toast.makeText(context, "wifi 连接配置不可用", 3000).show();
return;
}
while (!iptoready)
{
try
{
// 为了避免程序一直while循环,让它睡个100毫秒在检测……
            Thread.currentThread();
Thread.sleep(100);
}
catch (InterruptedException ie)
{
}
DhcpInfo dhcp = new WifiManageUtils(context).getDhcpInfo();
int ipInt = dhcp.gateway;
if (ipInt != 0)
{
iptoready = true;
}
}
wifiLock.acquire();
clientThread = new WifiClientThread(context);
clientThread.start();
}
});
  WifiClientThread客户端线程



public class WifiClientThread extends Thread
{
public Socket socket;
public Context context;
public Boolean isrun = true;
public static final int SERVERPORT = 8191;
public OutputStream os;
public InputStream in;
public WifiClientThread(Context context)
{
this.context = context;
}
public void run()
{
try
{
DhcpInfo dhcp = new WifiManageUtils(context).getDhcpInfo();
int ipInt = dhcp.gateway;
String serverip = String.valueOf(new StringBuilder()
.append((ipInt & 0xff)).append('.').append((ipInt >> 8) & 0xff)
.append('.').append((ipInt >> 16) & 0xff).append('.')
.append(((ipInt >> 24) & 0xff)).toString()
);
socket = new Socket(serverip, SERVERPORT);
new Thread(new Runnable()
{
@Override
public void run()
{
if (socket == null)
{
return;
}
System.out.println("client connect");
try
{
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/CHFS/000000000000";
if (android.os.Build.MODEL.contains("8812"))
{
path += "/camera/" + "camera_temp_name.jpg";
}
else
{
//                path += "/camera/" + "camera_temp_name.mp4";
path+="/ARChon-v1.1-x86_64.zip";
}
DataInputStream read = new DataInputStream(
new FileInputStream(new File(path)));
System.out.println(read.available());
String fileName = path.substring(path.lastIndexOf("/") + 1);// 获得文件名加类型

System.out.println(fileName);
os = socket.getOutputStream();
in = socket.getInputStream();
os.write((fileName + ";" + read.available())
.getBytes("utf-8"));// 将文件名和文件大小传给接收端
            os.flush();
byte[] data = new byte[1024];
int len = in.read(data);
String start = new String(data, 0, len);
int sendCountLen = 0;
if (start.equals("start"))
{
while ((len = read.read(data)) != -1)
{
os.write(data, 0, len);
sendCountLen += len;
}
os.flush();
os.close();
read.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}).start();
}
catch (IOException e)
// catch (Exception e)
    {
e.printStackTrace();
}
}
}
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-120928-1-1.html 上篇帖子: 让笔记本变身WIFI热点 下篇帖子: APP--简单的WIFI开发(带密码)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表