简体   繁体   English

通过android中的wifi连接发送和接收数据

[英]Sending and recieving data over wifi connection in android programatically

I am trying to make a app that communicates with a hotspot in my pc. 我正在尝试制作一个与PC中的热点进行通信的应用程序。 I am being able to connect to the hotspot but i am not being able to figure out how to send and recieve data in android. 我可以连接到热点,但无法弄清楚如何在android中发送和接收数据。 This is my code as of now in my app. 到目前为止,这是我的应用程序中的代码。

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// setup a wifi configuration
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "\"pigo\"";
wc.preSharedKey = "\"12345678\"";
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
// connect to and enable the connection
int netId = wifiManager.addNetwork(wc);
wifiManager.enableNetwork(netId, true);
wifiManager.setWifiEnabled(true);
stepinfo.setText("Initiating Connection . . .");

I have looked at other similar questions but nothing seems to be working with my app. 我看过其他类似的问题,但似乎没有任何工作与我的应用程序兼容。

By doing what you are doing above you can only connect to the hotspot of the computer (Windows PC - given you are using netsh wlan). 通过执行上述操作,您只能连接到计算机的热点(Windows PC-如果您使用的是netsh wlan)。 This will allow you to connect to your PC and at max share its internet. 这将允许您连接到PC,并最大程度地共享其Internet。 But to enable communication between your computer and your phone, you need to build an app over this layer. 但是要启用计算机和手机之间的通信,您需要在此层上构建一个应用程序。

What this app will do is. 这个程序将要做的是。 It will listen on specific port(s) on your PC and your mobile. 它将侦听您的PC和移动设备上的特定端口。 So when the connection through hotspot is established you will need to have a Socket and do Socket.connect(new InetAddress(IP, PORT)) . 因此,通过热点建立连接后,您将需要具有一个Socket并执行Socket.connect(new InetAddress(IP, PORT)) Lets say your computer listens on PORT_0 , then your mobile needs to do Socket.connect(new InetAddress(IP_COMPUTER, PORT_0)) . 假设您的计算机在PORT_0PORT_0 ,那么您的手机需要执行Socket.connect(new InetAddress(IP_COMPUTER, PORT_0))

This way you now have a socket which can be used for communication between your PC and your mobile. 这样,您现在有了一个可用于PC和手机之间通信的插座。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM