http://www.java2s.com/Open-Source/Android/Network/smartphone-networks/softaptest/mobed/yonsei/Main.java.htm
smartphone networks » softaptest » mobed » yonsei » Main.java
package softaptest.mobed.yonsei;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import android.app.Activity;
import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity {
/** Called when the activity is first created. */
Button btn_on, btn_off, btn_other;
public static final String WIFI_AP_STATE_CHANGED_ACTION = "android.net.wifi.WIFI_AP_STATE_CHANGED";
public static final String EXTRA_WIFI_AP_STATE = "wifi_state";
public static final int WIFI_AP_STATE_DISABLING = 0;
public static final int WIFI_AP_STATE_DISABLED = 1;
public static final int WIFI_AP_STATE_ENABLING = 2;
public static final int WIFI_AP_STATE_ENABLED = 3;
public static final int WIFI_AP_STATE_FAILED = 4;
private String TAG = "Soft AP Test";
private WifiManager mWifiManager;
private TextView serverStatus;
// default ip
public static String SERVERIP = "192.168.43.1";
// designate a port
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
private ServerSocket serverSocket;
private String receiveBuff = "";
//Variables for UCP broadcast
Thread uThread = new Thread(new udpThread());
private static final String REMOTE_KEY = "SSNUDP";
private static final int DISCOVERY_PORT = 9000;
private static final int LISTEN_PORT = 9000;
private static final int TIMEOUT_MS = 15000;
private static final String mChallenge = "Hey, SSN_UDP neighbors, from server";
private String udp_receive_buff = "";
public boolean setWifiApEnabled(boolean enabled)
{
if (enabled)
{ // disable WiFi in any case
mWifiManager.setWifiEnabled(false);
}
try {
WifiConfiguration netConfig = new WifiConfiguration();
netConfig.SSID = "SSN";
netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
netConfig.preSharedKey = "comsys505";
Method method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
return (Boolean) method.invoke(mWifiManager, netConfig, enabled);
} catch (Exception e) {
Log.e(TAG, "", e);
return false;
}
}
public int getWifiApState() {
try {
Method method = mWifiManager.getClass().getMethod("getWifiApState");
return (Integer) method.invoke(mWifiManager);
} catch (Exception e) {
Log.e(TAG, "", e);
return WIFI_AP_STATE_FAILED;
}
}
public class ServerThread implements Runnable
{
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Connected.");
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
receiveBuff = null;
while ((receiveBuff = in.readLine()) != null) {
Log.d("ServerActivity", receiveBuff);
handler.post(new Runnable() {
@Override
public void run()
{
// do whatever you want to the front end
// this is where you can be creative
serverStatus.setText(receiveBuff);
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
/*gets the IP address of your phone's network
*This function is used for TCP/IP communication via internet connection
*/
// private String getLocalIpAddress()
// {
// try {
// for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
// NetworkInterface intf = (NetworkInterface) en.nextElement();
// for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
// InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
// if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
// }
// }
// } catch (SocketException ex) {
// Log.e("ServerActivity", ex.toString());
// }
// return null;
// }
/*Section for UDP broadcast*/
public class udpThread implements Runnable
{
public void run()
{
try
{
DatagramSocket socket = new DatagramSocket(LISTEN_PORT);
socket.setBroadcast(true);
socket.setSoTimeout(TIMEOUT_MS);
// socket.setBroadcast(true);
//
// sendDiscoveryRequest(socket);
//
// Log.d("UDP_Activity", "UDP broadcast Sent");
socket.setBroadcast(true);
sendDiscoveryRequest(socket);
Log.d("UDP_Activity", "UDP broadcast Sent");
listenForResponses(socket);
handler.post(new Runnable() {
@Override
public void run()
{
// do whatever you want to the front end
// this is where you can be creative
serverStatus.setText(udp_receive_buff);
}
});
if(socket.getSoTimeout()>0)
{
Log.d(TAG, "Socket time out, is closing. TIMEOUT_MS: " + TIMEOUT_MS);
socket.close();
}
Log.d("UDP_Activity", "Listen to UDP response");
}
catch (IOException e)
{
Log.e(TAG, "Could not send discovery request", e);
}
}
}
/**
* Send a broadcast UDP packet containing a request for boxee services to
* announce themselves.
*
* @throws IOException
*/
// private boolean send_broadcast(byte msg[]) {
//
// try {
//
// int port = 9000;
//
// DatagramSocket socket = new DatagramSocket(port);
//
// InetAddress group = InetAddress.getByName("192.168.143.255"); //get_broadcast_address();
//
// Log.i(TAG, "Address: " + group.toString());
//
// socket.setBroadcast(true);
//
// DatagramPacket packet = new DatagramPacket(msg, msg.length, null, port);
//
// socket.send(packet);
//
// }
// catch (Exception e) {
// Log.e("Broadcast", "error: " + e.getMessage());
// return false;
// }
//
//
// return true;
// }
private void sendDiscoveryRequest(DatagramSocket socket) throws IOException
{
String data = String
.format(
"<bdp1 cmd=\"discover\" application=\"iphone_remote\" challenge=\"%s\" signature=\"%s\"/>",
mChallenge, getSignature(mChallenge));
Log.d(TAG, "Sending data " + data);
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
getBroadcastAddress(), DISCOVERY_PORT);
socket.send(packet);
}
/**
* Calculate the broadcast IP we need to send the packet along. If we send it
* to 255.255.255.255, it never gets sent. I guess this has something to do
* with the mobile network not wanting to do broadcast.
* @throws UnknownHostException
*/
private InetAddress getBroadcastAddress() throws UnknownHostException
{
DhcpInfo dhcp = mWifiManager.getDhcpInfo();
if (dhcp == null)
{
Log.d(TAG, "Could not get dhcp info");
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
//functions to calculate broadcastAddress from the current address
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
/**
* Listen on socket for responses, timing out after TIMEOUT_MS
*
* @param socket
* socket on which the announcement request was sent
* @throws IOException
*/
private void listenForResponses(DatagramSocket socket) throws IOException
{
byte[] buf = new byte[1024];
try
{
while (true)
{
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
udp_receive_buff = new String(packet.getData(), 0, packet.getLength());
Log.d(TAG, "Received response " + udp_receive_buff);
}
}
catch (SocketTimeoutException e)
{
Log.d(TAG, "Receive timed out");
}
}
/**
* Calculate the signature we need to send with the request. It is a string
* containing the hex md5sum of the challenge and REMOTE_KEY.
*
* @return signature string
*/
private String getSignature(String challenge)
{
MessageDigest digest;
byte[] md5sum = null;
try
{
digest = java.security.MessageDigest.getInstance("MD5");
digest.update(challenge.getBytes());
digest.update(REMOTE_KEY.getBytes());
md5sum = digest.digest();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
StringBuffer hexString = new StringBuffer();
for (int k = 0; k < md5sum.length; ++k)
{
String s = Integer.toHexString((int) md5sum[k] & 0xFF);
if (s.length() == 1)
hexString.append('0');
hexString.append(s);
}
return hexString.toString();
}
/*Section for TCP/IP communication client part*/
public class ClientThread implements Runnable
{
public void run()
{
boolean connected;
try
{
String serverIp="192.168.43.224";
InetAddress serverAddr = InetAddress.getByName(serverIp);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, SERVERPORT);
// socket.setSoTimeout(TCP_TIMEOUT_MS);
connected = true;
while (connected)
{
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
// where you issue the commands
out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
}
catch (Exception e)
{
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
}
catch (Exception e)
{
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
btn_on = (Button) findViewById(R.id.ButtonOn);
btn_off = (Button) findViewById(R.id.ButtonOff);
btn_other = (Button) findViewById(R.id.ButtonOther);
udp_receive_buff = "";
btn_on.setOnClickListener(
new OnClickListener()
{
public void onClick(View v)
{
setWifiApEnabled(true);
}
});
btn_off.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
setWifiApEnabled(false);
}
});
btn_other.setOnClickListener
(
new OnClickListener() {
public void onClick(View v) {
uThread.stop();
uThread.start();
// String hello = "Hello world!";
//
// if (send_broadcast(hello.getBytes()))
// Log.i("Broadcast", "Everything is good!");
}
}
);
serverStatus = (TextView) findViewById(R.id.serverStatus);
// SERVERIP = getLocalIpAddress();
//This part is for TCP/IP communication
// Thread fst = new Thread(new ServerThread());
// fst.start();
}
@Override
protected void onStop()
{
uThread.stop();
super.onStop();
}
@Override
public void onDestroy()
{
uThread.stop();
super.onDestroy();
}
}