2012-02-08 55 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(); 
}