与2个Android设备的TCP连接

时间:2013-04-07 13:06:06

标签: android tcp


我想让一个Android设备成为一个可以制作HotSpot的服务器,当另一个Android设备连接到该HotSpot时,它可以通过TCP连接与服务器通信。 创建HotSpot并连接到它工作正常,但我无法通过TCP连接。 我试图通过IP连接后连接到HotSpot:

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ip = wifiInfo.getIpAddress();

但是服务器和客户端等待套接字连接,所以这个IP可能错了吗?如果错了,我怎样才能通过TCP连接到正确的IP连接?

以下是客户的代码:

public class LoginActivity extends Activity {

    private static final String AP_NAME = "\"MobileEduPlatform\"";
    private static final String TAG = "LoginActivity";

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

    public void connectToHS(){
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifi.disconnect();
        wifi.enableNetwork(configureNetwork(), true);
    }

    public int configureNetwork(){
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiConfiguration config = new WifiConfiguration();
        config.status = WifiConfiguration.Status.ENABLED;
        config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        config.SSID = AP_NAME;
        int id =  wifi.addNetwork(config);
        wifi.saveConfiguration();
        wifi.enableNetwork(id, true);
        return id;
    }

    public void onClick2(View view){
        String otherIP = "";        
        String ip = getIpAddr();        
        new TCPClient(this).execute(ip);  
    }

    public String getIpAddr() {
           WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
           WifiInfo wifiInfo = wifiManager.getConnectionInfo();
           int ip = wifiInfo.getIpAddress();

           String ipString = String.format(
            "%d.%d.%d.%d",
           (ip & 0xff),
           (ip >> 8 & 0xff),
           (ip >> 16 & 0xff),
           (ip >> 24 & 0xff));

           return ipString;
    }
}

public class TCPClient extends AsyncTask<String, Void, Boolean> {
    private int TCP_SERVER_PORT = 55000;

    @Override
    protected Boolean doInBackground(String... arg0) {
        runTcpClient(arg0[0]);
        return true;
    }   
    private void runTcpClient(String ip) {

        try {
            Socket s = new Socket(ip, TCP_SERVER_PORT);
            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

            String outMsg = "TCP connecting to " + TCP_SERVER_PORT + System.getProperty("line.separator"); 
            out.write(outMsg);
            out.flush();

            String inMsg = in.readLine() + System.getProperty("line.separator");
            s.close();

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

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

        } 
    }
}

服务器:

public class WifiAPActivity extends Activity {
    private boolean wasAPEnabled = false;
    private static WifiAP wifiAp;
    private WifiManager wifi;
    private static Button btnWifiToggle;

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

        btnWifiToggle = (Button) findViewById(R.id.btnWifiToggle);
        wifiAp = new WifiAP();
        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

        btnWifiToggle.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                wifiAp.toggleWiFiAP(wifi, WifiAPActivity.this);
            }
        });

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_DIM_BEHIND);       
    }

    public void onClick(View view){
        new TCPServer2(this).execute("");
    }
}

public class TCPServer2 extends AsyncTask<String, Void, Boolean>{
    private Exception exception;
    private int TCP_SERVER_PORT = 55000;

    protected Boolean doInBackground(String... urls) {
        runTcpServer();
        return true;            
    }

    private void runTcpServer() {       
        ServerSocket ss = null;

        try {
            ss = new ServerSocket(TCP_SERVER_PORT);
            Socket s = ss.accept();

            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            String incomingMsg = in.readLine() + System.getProperty("line.separator");

            String outgoingMsg = "goodbye from port " + TCP_SERVER_PORT + System.getProperty("line.separator");
            out.write(outgoingMsg);
            out.flush();

            s.close();

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

        } finally {
            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

0 个答案:

没有答案