java ssl socket example

ssl socket connection with multi threading application. 

Server




  1. package Test2;

  2. import java.awt.BorderLayout;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.io.IOException;
  6. import java.io.ObjectInputStream;
  7. import java.io.ObjectOutputStream;
  8. import java.net.InetAddress;
  9. import java.security.cert.Certificate;
  10. import java.security.cert.X509Certificate;
  11. import java.util.ArrayList;

  12. import javax.net.ssl.SSLServerSocket;
  13. import javax.net.ssl.SSLServerSocketFactory;
  14. import javax.net.ssl.SSLSession;
  15. import javax.net.ssl.SSLSocket;
  16. import javax.swing.JFrame;
  17. import javax.swing.JOptionPane;
  18. import javax.swing.JScrollPane;
  19. import javax.swing.JTextArea;
  20. import javax.swing.JTextField;

  21. public class Server {
  22. public static ArrayList<String> list_user = new ArrayList<String>();
  23. public static ArrayList<String> list_verify = new ArrayList<String>();
  24. public static int port = 8005;
  25. public static void main(String[] args) {
  26. list_verify.add("101");
  27. list_verify.add("102");
  28. list_verify.add("103");
  29. list_verify.add("104");
  30. list_verify.add("105");
  31. try {
  32. SSLServerSocketFactory factory=(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
  33.        SSLServerSocket sslserversocket = (SSLServerSocket) factory.createServerSocket(port, 0, InetAddress.getLocalHost());
  34.        System.out.println("Server running in :" + InetAddress.getLocalHost() + ":" + port);
  35.        String[] suites = sslserversocket.getSupportedCipherSuites();
  36.        /*for(String s:suites){
  37.         System.out.println(s);
  38.        }*/
  39.        sslserversocket.setEnabledCipherSuites(suites);
  40.        while (true) {
  41.        SSLSocket socket=(SSLSocket) sslserversocket.accept();
  42. /*       
  43.        SSLSession session = ((SSLSocket) socket).getSession();
  44.        Certificate[] cchain2 = session.getLocalCertificates();*/
  45.       
  46.       
  47. Runnable accept = new Runnable() {
  48. @Override
  49. public void run() {
  50. JFrame frame = new JFrame("Server");
  51. String currentUser="";
  52. try {
  53. ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
  54. String username = (String) ois.readObject();
  55.    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

  56. if (list_verify.contains(username)) {
  57. if (!list_user.contains(username)) {
  58. list_user.add(username);
  59. currentUser=username;
  60. oos.writeObject("1");
  61. System.out.println("connected to : " + username);
  62. //JFrame frame = new JFrame("Server");
  63. frame.addWindowListener(new java.awt.event.WindowAdapter() {
  64.    @Override
  65.    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
  66.     //frame.dispose();
  67.     try {
  68. oos.close();
  69. ois.close();
  70. } catch (IOException e) {

  71. e.printStackTrace();
  72. }
  73.    
  74.    }
  75. });

  76. frame.setVisible(true);
  77. JTextField userText = new JTextField();
  78. userText.setEditable(false);
  79. userText.addActionListener(new ActionListener() {
  80. public void actionPerformed(ActionEvent event) {
  81. sendMessage(oos, event.getActionCommand());
  82. userText.setText("");
  83. }
  84. });
  85. ;

  86. frame.add(userText, BorderLayout.NORTH);
  87. JTextArea chatWindow = new JTextArea();
  88. chatWindow.setEditable(false);
  89. frame.add(new JScrollPane(chatWindow));
  90. frame.setSize(300, 150);
  91. chatWindow.append("connected to : " + username);
  92. userText.setEditable(true);

  93. do {
  94. try {
  95. username = (String) ois.readObject();
  96. chatWindow.append("\n " + username);
  97. } catch (ClassNotFoundException classNotFoundException) {
  98. System.out.println("close");
  99. chatWindow.append("\n Dont know the Object type ");
  100. chatWindow.append("\n connection close.. ");
  101. }

  102. } while (!username.equals("END"));

  103. } else {
  104. oos.writeObject("2");
  105. }
  106. } else {
  107. oos.writeObject("0");
  108. }

  109. } catch (IOException e) {
  110. System.out.println("client disconnected ");
  111. frame.dispose();
  112. list_user.remove(currentUser);
  113. //Thread.currentThread().interrupt();
  114. // chatWindow.append("Diss");
  115. // userText.setEditable(false);
  116. // e.printStackTrace();
  117. } catch (ClassNotFoundException e) {
  118. e.printStackTrace();

  119. }

  120. }};
  121. new Thread(accept).start();
  122.        }
  123. } catch (IOException e) {
  124. JOptionPane.showMessageDialog(null, "Server already running in the same port");
  125. System.out.println("Ip and port Already bind");
  126. }
  127.      

  128. }
  129. public static void sendMessage(ObjectOutputStream oos, String message) {
  130. try {
  131. oos.writeObject(message);
  132. } catch (IOException e) {
  133. e.printStackTrace();
  134. }
  135. }

  136. }

Client




  1. package Test2;

  2. import java.awt.BorderLayout;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.io.IOException;
  6. import java.io.ObjectInputStream;
  7. import java.io.ObjectOutputStream;
  8. import java.net.UnknownHostException;

  9. import javax.net.ssl.HandshakeCompletedEvent;
  10. import javax.net.ssl.HandshakeCompletedListener;
  11. import javax.net.ssl.SSLSocket;
  12. import javax.net.ssl.SSLSocketFactory;
  13. import javax.swing.JFrame;
  14. import javax.swing.JOptionPane;
  15. import javax.swing.JScrollPane;
  16. import javax.swing.JTextArea;
  17. import javax.swing.JTextField;

  18. public class Client {

  19. public static void main(String[] args) {
  20. String host = "localhost";
  21. int port = 8005;
  22. String username = JOptionPane.showInputDialog(null, "IP: " + host + ":" + port);
  23. JFrame frame = new JFrame("Client");
  24. try {

  25. SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
  26. SSLSocket socket = (SSLSocket) factory.createSocket(host, port);

  27. String[] suites = socket.getSupportedCipherSuites();
  28. socket.setEnabledCipherSuites(suites);

  29. socket.addHandshakeCompletedListener(new MyHandshakeListener());
  30. socket.startHandshake();

  31. System.out.println("Just connected to " + socket.getRemoteSocketAddress());
  32. ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
  33. oos.writeObject(username);

  34. ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
  35. String response = (String) ois.readObject();
  36. //JFrame frame = new JFrame("Client");
  37. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  38. frame.setVisible(true);
  39. JTextField userText = new JTextField();
  40. userText.setEditable(false);
  41. userText.addActionListener(new ActionListener() {
  42. public void actionPerformed(ActionEvent event) {
  43. sendMessage(oos, event.getActionCommand());
  44. userText.setText("");
  45. }
  46. });
  47. ;

  48. frame.add(userText, BorderLayout.NORTH);
  49. JTextArea chatWindow = new JTextArea();
  50. chatWindow.setEditable(false);
  51. frame.add(new JScrollPane(chatWindow));
  52. frame.setSize(300, 150);
  53. if (response.equalsIgnoreCase("1")) {
  54. chatWindow.append("connected......");
  55. userText.setEditable(true);
  56. do {
  57. try {
  58. response = (String) ois.readObject();
  59. chatWindow.append("\n " + response);
  60. } catch (ClassNotFoundException classNotFoundException) {
  61. chatWindow.append("\n Dont know the Object type ");
  62. chatWindow.append("\n connection close.. ");
  63. }

  64. } while (!response.equals(" END"));
  65. }
  66. if (response.equalsIgnoreCase("0")) {
  67. chatWindow.append("\n refused , not authorised....");
  68. }
  69. if (response.equalsIgnoreCase("2")) {
  70. frame.dispose();
  71. JOptionPane.showMessageDialog(null, "already connected");
  72. }

  73. } catch (UnknownHostException e) {
  74. // TODO Auto-generated catch block
  75. e.printStackTrace();
  76. } catch (IOException e) {
  77. frame.dispose();
  78. }
  79.  catch (ClassNotFoundException e) {
  80. // TODO Auto-generated catch block
  81. e.printStackTrace();
  82. }
  83. }
  84. public static void sendMessage(ObjectOutputStream oos, String message) {
  85. try {
  86. oos.writeObject(message);
  87. } catch (IOException e) {
  88. // TODO Auto-generated catch block
  89. e.printStackTrace();
  90. }
  91. }

  92. }
  93. class MyHandshakeListener implements HandshakeCompletedListener {
  94.   public void handshakeCompleted(HandshakeCompletedEvent e) {
  95.     System.out.println("Handshake succesful!");
  96.     System.out.println("Using cipher suite: " + e.getCipherSuite());
  97.   }
  98. }
  99.    

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations