Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am doing socket communication through follwing IP address it working but no i want to do communication in ssl mode but how can I change InetAddress serverAddr = InetAddress.getByName("192.168.1.2"); to SSL.

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);

     }

}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
195 views
Welcome To Ask or Share your Answers For Others

1 Answer

Create SSLSocket instead of Socket. Rest is the same.

SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("192.168.1.2", 12345);

You may want to add aditional SSL properties. You have to do it ealier:

To authenticate the server, the client's trust store must contain the server's certificate. Client SSL with server authentication is enabled by the URL attribute ssl or the property ssl set to peerAuthentication. In addition, the system properties javax.net.ssl.trustStore and javax.net.ssl.trustStorePassword need to be set.:

System.setProperty("javax.net.ssl.trustStore","clientTrustStore.key");
System.setProperty("javax.net.ssl.trustStorePassword","qwerty");

If the server does client authentication, the client will need a key pair and a client certificate:

System.setProperty("javax.net.ssl.keyStore","clientKeyStore.key");
System.setProperty("javax.net.ssl.keyStorePassword","qwerty");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...