2011-07-21 59 views
2

可能重複:
how to do ssl socket programming如何做到安全套接字通信的Android筆記本電腦

我使用無線router.But如何通過Socket做從Android作爲客戶機和筆記本電腦作爲服務器的通信如果我想要安全地進行通信。這是我在eclipse

public class TCPClient implements Runnable { 

    public void run() { 

    try { 

     InetAddress serverAddr = InetAddress.getByName("192.168.1.2"); 

      Log.d("TCP", "C: Connecting..."); 

      Socket socket = new Socket(serverAddr,12345); 

      String message = "Hello from Client android emulator"; 
       try { 

        Log.d("TCP", "C: Sending: '" + message + "'"); 

        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true); 

        out.println(message); 

        Log.d("TCP", "C: Sent."); 

       Log.d("TCP", "C: Done."); 



     } catch(Exception e) { 

      Log.e("TCP", "S: Error", e); 
       } finally { 

        socket.close(); 

        } 
    } catch (Exception e) { 

      Log.e("TCP", "C: Error", e); 

    } 

} 

} 

這裏Android的代碼是在Netbean服務器代碼,該代碼工作,與Android通信。我必須做些什麼改變?

public class TCPDesktopServer implements Runnable{ 



public static final String SERVERIP = "10.0.2.15"; 

public static final int SERVERPORT = 12345; 



public void run() { 

    try { 

     System.out.println("S: Connecting..."); 

     ServerSocket serverSocket = new ServerSocket(SERVERPORT); 

     while (true) { 

      Socket client = serverSocket.accept(); 

      System.out.println("S: Receiving..."); 

      try { 
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); 

        String str = in.readLine(); 

        System.out.println("S: Received: '" + str + "'"); 
      } catch(Exception e) { 

        System.out.println("S: Error"); 

        e.printStackTrace(); 

      } finally { 
        client.close(); 
        System.out.println("S: Done."); 
       } 
     } 

    } catch (Exception e) { 

     System.out.println("S: Error"); 

     e.printStackTrace(); 
    } 
} 

public static void main (String a[]) { 

    Thread desktopServerThread = new Thread(new TCPDesktopServer()); 

    desktopServerThread.start(); 

} 

}

回答

0

好像你需要使用javax.crypto.CipherOutputStream/CipherInputStream,或者如果你想要一個更標準化的方法,你可以嘗試阿帕奇百科全書(HTTP://commons.apache。 org /),其中有一個基本的SSL實現。

0

你可以很容易地使用SSLSocket類,它是基礎Java發行版的一部分。如果您在驗證證書時遇到問題,您可以使用教程向您展示如何允許自簽名證書和不匹配的主機名。

+0

對不起,但如何解決InetAddress serverAddr = InetAddress.getByName(「192.168.1.2」);進入hhtps –

相關問題