2017-03-30

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. }


6 comments:

  1. package server.app;

    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Client extends JFrame{


    private static final long serialVersionUID = 1L;
    private JTextField userText;
    private JTextArea chatWindow;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private String message="";
    private String serverIP;
    private Socket connection;

    public Client(String host) throws Exception
    {
    super("Client ");
    serverIP=host;

    String userid = (String)JOptionPane.showInputDialog("Enter ID");
    connectToServer();
    setupStreams();
    output.writeObject(userid);
    message=(String)input.readObject();
    if(message=="reject" || message.equalsIgnoreCase("reject")){
    closeCrap();
    }

    userText= new JTextField();
    userText.setEditable(false);
    userText.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    {
    sendMessage(event.getActionCommand());
    userText.setText("");
    }
    });
    add(userText,BorderLayout.NORTH);
    chatWindow=new JTextArea();
    chatWindow.setEditable(false);
    add(new JScrollPane(chatWindow),BorderLayout.CENTER);
    setSize(300,150);
    setVisible(true);
    }

    public void startRunning()
    {
    try{
    //connectToServer();
    //setupStreams();
    whileChatting();
    }catch(EOFException eofException)
    {
    showMessage("\n Client Treminated connection !!!!!!");
    }catch(IOException ioException)
    {
    ioException.printStackTrace();
    }finally{
    closeCrap();
    }
    }

    private void connectToServer() throws IOException
    {
    showMessage(" Attempting Connection........\n");
    connection=new Socket(InetAddress.getByName(serverIP),8001);
    showMessage("Connected to : " + connection.getInetAddress().getHostName());
    }


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

    private void whileChatting() throws IOException
    {
    ableToType(true);
    do{
    try{
    message=(String)input.readObject();
    showMessage("\n " + message);
    }catch(ClassNotFoundException classNotFoundException)
    {
    showMessage("\n Dont know the Object type ");
    }

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

    }

    private void closeCrap()
    {
    showMessage("\n Closing crop down");
    ableToType(false);
    try{
    output.close();
    input.close();
    connection.close();
    }catch(IOException ioException)
    {
    ioException.printStackTrace();
    }
    }


    private void sendMessage(String message)
    {
    try{
    output.writeObject("CLIENT - " + message);
    output.flush();
    showMessage("\n CLIENT - " + message);
    }catch(IOException ioException)
    {
    chatWindow.append("\n Something messed up sending message Host !!!!!!");
    }
    }


    private void showMessage(final String m)
    {
    SwingUtilities.invokeLater(
    new Runnable(){
    public void run()
    {
    chatWindow.append(m);
    }
    });
    }
    private void ableToType(final boolean tof)
    {
    SwingUtilities.invokeLater(
    new Runnable(){
    public void run()
    {
    userText.setEditable(tof);
    }
    });
    }





    }


    package server.app;

    import javax.swing.JFrame;
    public class ClientTest {
    public static void main(String[] args) throws Exception {
    Client charlie;
    charlie=new Client("localhost");
    charlie.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    charlie.startRunning();

    }

    }

    ReplyDelete
  2. import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    import java.net.UnknownHostException;

    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;

    public class Client {

    public static Socket socket;
    public static String ip = "192.168.137.71";
    public static int port = 8005;
    public static ObjectOutputStream oos;

    public static void main(String[] args) {
    String username = JOptionPane.showInputDialog(null, "IP: " + ip + ":" + port);
    System.out.println(username);
    JTextArea chatWindow;
    JTextField userText;
    try {
    socket = new Socket(ip, port);
    oos = new ObjectOutputStream(socket.getOutputStream());
    oos.writeObject(username);

    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
    String response = (String) ois.readObject();
    JFrame frame = new JFrame("Client");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    userText = new JTextField();
    userText.setEditable(false);
    userText.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
    sendMessage(event.getActionCommand());
    userText.setText("");
    }
    });
    ;

    frame.add(userText, BorderLayout.NORTH);
    chatWindow = new JTextArea();
    chatWindow.setEditable(false);
    frame.add(new JScrollPane(chatWindow));
    frame.setSize(300, 150);
    if (response.equalsIgnoreCase("1")) {
    chatWindow.append("connected......");
    userText.setEditable(true);
    do {
    try {
    response = (String) ois.readObject();
    chatWindow.append("\n " + response);
    } catch (ClassNotFoundException classNotFoundException) {
    chatWindow.append("\n Dont know the Object type ");
    chatWindow.append("\n connection close.. ");
    }

    } while (!response.equals(" END"));
    }
    if (response.equalsIgnoreCase("0")) {
    chatWindow.append("\n refused , not authorised....");
    }
    if (response.equalsIgnoreCase("2")) {
    JOptionPane.showMessageDialog(null, "already connected");
    }


    } catch (UnknownHostException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    System.out.println("dis");
    //chatWindow.append("Diss");
    //userText.setEditable(false);
    //e.printStackTrace();
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    public static void sendMessage(String message) {
    try {
    oos.writeObject(message);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    }

    ReplyDelete
  3. import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.ArrayList;

    import javax.swing.DefaultListModel;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;

    public class Server {
    public static ServerSocket server;
    public static ArrayList list_sockets = new ArrayList();
    public static ArrayList list_client_status = new ArrayList();
    public static ArrayList list_data = new ArrayList();
    public static DefaultListModel list_client_model;
    public static ArrayList list_user = new ArrayList();
    public static ArrayList list_verify = new ArrayList();
    public static String ip = "";
    public static int port = 8005;
    public static ObjectOutputStream oos ;

    public static void main(String[] args) {
    list_verify.add("101");
    list_verify.add("102");
    list_verify.add("103");
    list_verify.add("104");
    list_verify.add("105");

    try {
    ip = InetAddress.getLocalHost().getHostAddress() + ":" + port;
    try {
    server = new ServerSocket(port, 0, InetAddress.getLocalHost());
    System.out.println("Server running in :"+ InetAddress.getLocalHost() +":"+port);
    new Thread(accept).start();
    } catch (IOException e) {
    e.printStackTrace();
    }

    } catch (UnknownHostException e) {
    e.printStackTrace();
    }
    }
    private static Runnable accept = new Runnable() {
    @Override
    public void run() {
    new Thread(send).start();
    new Thread(receive).start();

    while (true) {
    JTextArea chatWindow ;
    JTextField userText ;
    try {

    Socket socket = server.accept();
    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
    String username = (String) ois.readObject();
    oos = new ObjectOutputStream(socket.getOutputStream());

    ReplyDelete

  4. if(list_verify.contains(username)){
    if(!list_user.contains(username)){
    list_user.add(username);
    oos.writeObject("1");
    System.out.println("connected to : "+username);
    JFrame frame = new JFrame("Server");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    userText = new JTextField();
    userText.setEditable(false);
    userText.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
    sendMessage(event.getActionCommand());
    userText.setText("");
    }
    });
    ;

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

    do {
    try {
    username = (String) ois.readObject();
    chatWindow.append("\n " + username);
    } catch (ClassNotFoundException classNotFoundException) {
    chatWindow.append("\n Dont know the Object type ");
    chatWindow.append("\n connection close.. ");
    }

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

    }else {
    oos.writeObject("2");
    }
    }else {
    oos.writeObject("0");
    }

    } catch (IOException e) {
    System.out.println("Diss");
    //chatWindow.append("Diss");
    //userText.setEditable(false);
    //e.printStackTrace();
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }

    }

    }
    };
    private static Runnable send = new Runnable() {
    @Override
    public void run() {

    }
    };
    private static Runnable receive = new Runnable() {
    @Override
    public void run() {

    }
    };
    public static void sendMessage(String message) {
    try {
    oos.writeObject(message);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }

    ReplyDelete
  5. package Test;

    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    import java.net.UnknownHostException;

    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;

    public class Client {

    public static Socket socket;
    public static String ip = "58.2.2.231";
    public static int port = 8005;


    public static void main(String[] args) {
    String username = JOptionPane.showInputDialog(null, "IP: " + ip + ":" + port);
    System.out.println(username);
    JFrame frame = new JFrame("Client");

    try {
    socket = new Socket(ip, port);
    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
    oos.writeObject(username);

    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
    String response = (String) ois.readObject();
    //JFrame frame = new JFrame("Client");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    JTextField userText = new JTextField();
    userText.setEditable(false);
    userText.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
    sendMessage(oos, event.getActionCommand());
    userText.setText("");
    }
    });
    ;

    frame.add(userText, BorderLayout.NORTH);
    JTextArea chatWindow = new JTextArea();
    chatWindow.setEditable(false);
    frame.add(new JScrollPane(chatWindow));
    frame.setSize(300, 150);
    if (response.equalsIgnoreCase("1")) {
    chatWindow.append("connected......");
    userText.setEditable(true);
    do {
    try {
    response = (String) ois.readObject();
    chatWindow.append("\n " + response);
    } catch (ClassNotFoundException classNotFoundException) {
    chatWindow.append("\n Dont know the Object type ");
    chatWindow.append("\n connection close.. ");
    }

    } while (!response.equals(" END"));
    }
    if (response.equalsIgnoreCase("0")) {
    chatWindow.append("\n refused , not authorised....");
    }
    if (response.equalsIgnoreCase("2")) {
    JOptionPane.showMessageDialog(null, "already connected");
    }

    } catch (UnknownHostException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    System.out.println("disconnected from server");
    frame.dispose();
    // chatWindow.append("Diss");
    // userText.setEditable(false);
    // e.printStackTrace();
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    public static void sendMessage(ObjectOutputStream oos, String message) {
    try {
    oos.writeObject(message);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    }

    ReplyDelete