2012-02-08 56 views
3

是否可以在android手機上啓用WiFi共享/熱點,並通過兩種不同的應用將其配置爲服務器和客戶端?啓用WiFi熱點的設備上的服務器和客戶端

+0

您是指Wifi客戶端中的客戶端還是TCP/UDP客戶端中的客戶端? – Badmaster 2013-10-25 09:05:25

+0

正如在TCP/UDP客戶端... – 2013-11-12 08:05:30

+0

是,這是可能的 – 2017-07-11 16:35:02

回答

1

您不需要兩個不同的應用程序。在一個應用程序中集成兩個功能。

對於客戶端實現使用java.net.Socket,對於服務器端實現使用java.net.ServerSocket

服務器端代碼:

呼叫startServer()啓動服務器在端口監聽數據(把你的願望)。

void startServer() throws IOException { 
     new Thread(() -> { 
      try { 
       serverSocket = new ServerSocket(9809); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      Socket socket = null; 
      try { 
       socket = serverSocket.accept(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      DataInputStream stream = null; 
      try { 
       if (socket != null) { 
        stream = new DataInputStream(socket.getInputStream()); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      String gotdata = null; 
      try { 
       if (stream != null) { 
        gotdata = stream.readUTF(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      try { 
       assert socket != null; 
       socket.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      try { 
       serverSocket.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

      System.out.println("THE DATA WE HAVE GOT :"+gotdata) 

     }).start(); 

客戶端代碼: 在這裏,你應該把作爲在第6行服務器設備的IP地址(對於我來說,這是192.168.1.100)。

撥打sendData()向作爲服務器的設備發送數據。

void sendData() { 
    new Thread(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       Socket socket = new Socket("192.168.1.100", 9809); 
       DataOutputStream stream = new DataOutputStream(socket.getOutputStream()); 
       stream.writeUTF("Some data here"); 
       stream.flush(); 
       stream.close(); 
       socket.close(); 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         System.out.println("Done!"); 
        } 
       }); 
      } catch (Exception e) { 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         System.out.println("Fail!"); 
        } 
       }); 
       e.printStackTrace(); 
      } 
     } 
    }).start(); 
}