Java Socket Programming (Java Networking Tutorial)

Java Socket Programming using swing. instant messaging program.

Server




  1. import java.io.*;
  2. import java.net.ServerSocket;
  3. import java.net.Socket;

  4. import javax.swing.*;

  5. import java.awt.*;
  6. import java.awt.event.*;
  7. public class server extends JFrame
  8. {
  9. private JTextField userText;
  10. private JTextArea chatWindow;
  11. private ObjectOutputStream output;
  12. private ObjectInputStream input;
  13. private ServerSocket servers;
  14. private Socket connection;

  15. public server()
  16. {
  17. super("Chat Messenger");
  18. userText=new JTextField();
  19. userText.setEditable(false);
  20. userText.addActionListener(
  21. new ActionListener(){
  22. public void actionPerformed(ActionEvent event){
  23. sendMessage(event.getActionCommand());
  24. userText.setText("");
  25. }
  26. }
  27. );
  28. add(userText,BorderLayout.NORTH);
  29. chatWindow=new JTextArea();
  30. chatWindow.setEditable(false);
  31. add(new JScrollPane(chatWindow));
  32. setSize(300,150);
  33. setVisible(true);
  34. }


  35. public void startRunning()
  36. {
  37. try{
  38. servers=new ServerSocket(6789,100);
  39. while(true)
  40. {
  41. try{
  42. waitForConnection();
  43. setupStreams();
  44. whileChatting();
  45. }catch(EOFException eofException)
  46. {
  47. showMessage("\n Server Ended the connection! ");
  48. }
  49. finally
  50. {
  51. closeCrap();
  52. }

  53. }
  54. }catch(IOException ioException)
  55. {
  56. ioException.printStackTrace();
  57. }
  58. }
  59. private void waitForConnection() throws IOException
  60. {
  61. showMessage("wating for someone for connect ....\n");
  62. connection=servers.accept();
  63. showMessage("Now Connected to "+connection.getInetAddress().getHostName());
  64. }
  65. private void setupStreams()throws IOException
  66. {
  67. output=new ObjectOutputStream(connection.getOutputStream());
  68. output.flush();
  69. input=new ObjectInputStream(connection.getInputStream());
  70. showMessage("\n Streams are now setup !!\n");
  71. }

  72. private void whileChatting()throws IOException
  73. {
  74. String message="Your are Connected!!!";
  75. sendMessage(message);
  76. ableToType(true);

  77. do
  78. {
  79.        try
  80.         {
  81. message=(String)input.readObject();
  82. showMessage("\n"+message);
  83.             }
  84.        catch(ClassNotFoundException classNotFoundException)
  85.        {

  86.        }

  87. }
  88. while(!message.equals("CLIENT - END"));
  89. }

  90. private void closeCrap()
  91. {
  92. showMessage("\n Clossing Connection!!!!!!!! \n");
  93. ableToType(false);
  94. try{
  95. output.close();
  96. input.close();
  97. connection.close();
  98. }catch(IOException ioException)

  99. {
  100. ioException.printStackTrace();
  101. }
  102. }

  103. private void sendMessage(String message)
  104. {
  105. try{
  106. output.writeObject("SERVER - "+ message);
  107. output.flush();
  108. showMessage("\n SERVER - " + message);
  109. }catch(IOException ioException)
  110. {
  111. chatWindow.append("\n your can't send Message");
  112. }
  113. }

  114. private void showMessage(final String text)
  115. {
  116. SwingUtilities.invokeLater(
  117.    new Runnable()
  118. {
  119.          public void run()
  120.           {
  121.     chatWindow.append(text);
  122.           }
  123. }
  124. );
  125. }


  126. private void ableToType(final boolean tof)
  127. {
  128. SwingUtilities.invokeLater(
  129.    new Runnable()
  130. {
  131.          public void run()
  132.           {
  133.    userText.setEditable(tof);
  134.           }
  135. }
  136. );
  137. }


  138. }

ServerTest



  1. import javax.swing.JFrame;
  2. public class ServerTest {
  3. public static void main(String[] args) {
  4. server sally=new server();
  5.          sally.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  6.          sally.startRunning();
  7. }

  8. }

Client



  1. import java.io.*;
  2. import java.net.*;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import javax.swing.*;
  6. public class Client extends JFrame{

  7. private JTextField userText;
  8. private JTextArea chatWindow;
  9. private ObjectOutputStream output;
  10. private ObjectInputStream input;
  11. private String message="";
  12. private String serverIP;
  13. private Socket connection;

  14. public Client(String host)
  15. {
  16. super("Client ");
  17. serverIP=host;
  18. userText= new JTextField();
  19. userText.setEditable(false);
  20. userText.addActionListener(new ActionListener(){
  21. public void actionPerformed(ActionEvent event)
  22. {
  23. sendMessage(event.getActionCommand());
  24. userText.setText("");
  25. }
  26. });
  27. add(userText,BorderLayout.NORTH);
  28. chatWindow=new JTextArea();
  29. chatWindow.setEditable(false);
  30. add(new JScrollPane(chatWindow),BorderLayout.CENTER);
  31. setSize(300,150);
  32. setVisible(true);
  33. }

  34. public void startRunning()
  35. {
  36. try{
  37. connectToServer();
  38. setupStreams();
  39. whileChatting();
  40. }catch(EOFException eofException)
  41. {
  42. showMessage("\n Client Treminated connection !!!!!!");
  43. }catch(IOException ioException)
  44. {
  45. ioException.printStackTrace();
  46. }finally{
  47. closeCrap();
  48. }
  49. }

  50. private void connectToServer() throws IOException
  51. {
  52. showMessage(" Attempting Connection........\n");
  53. connection=new Socket(InetAddress.getByName(serverIP),6789);
  54. showMessage("Connected to : " +  connection.getInetAddress().getHostName());
  55. }


  56. private void setupStreams() throws IOException
  57. {
  58. output=new ObjectOutputStream(connection.getOutputStream());
  59. output.flush();
  60. input=new ObjectInputStream(connection.getInputStream());
  61. showMessage("\n your Message are Now good to go !!!!!!!!! \n");
  62. }

  63. private void whileChatting() throws IOException
  64. {
  65. ableToType(true);
  66. do{
  67. try{
  68. message=(String)input.readObject();
  69. showMessage("\n " + message);
  70. }catch(ClassNotFoundException classNotFoundException)
  71. {
  72. showMessage("\n Dont know the Object type ");
  73. }

  74. }while(!message.equals("SERVER - END"));

  75. }

  76. private void closeCrap()
  77. {
  78. showMessage("\n Closing crop down");
  79. ableToType(false);
  80. try{
  81. output.close();
  82. input.close();
  83. connection.close();
  84. }catch(IOException ioException)
  85. {
  86. ioException.printStackTrace();
  87. }
  88. }


  89. private void sendMessage(String message)
  90. {
  91. try{
  92. output.writeObject("CLIENT - " + message);
  93. output.flush();
  94. showMessage("\n CLIENT - " + message);
  95. }catch(IOException ioException)
  96. {
  97. chatWindow.append("\n Something messed up sending message Host !!!!!!");
  98. }
  99. }


  100. private void showMessage(final String m)
  101. {
  102. SwingUtilities.invokeLater(
  103. new Runnable(){
  104. public void run()
  105. {
  106. chatWindow.append(m);
  107. }
  108. });
  109. }
  110. private void ableToType(final boolean tof)
  111. {
  112. SwingUtilities.invokeLater(
  113. new Runnable(){
  114. public void run()
  115. {
  116. userText.setEditable(tof);
  117. }
  118. });
  119. }





  120. }

ClientTest



  1. import javax.swing.JFrame;
  2. public class ClientTest {
  3. public static void main(String[] args) {
  4. Client charlie;
  5. charlie=new Client("192.168.1.6");
  6. charlie.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  7. charlie.startRunning();

  8. }

  9. }


Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation