title: Chat Program: Client to Server Connectivity Issue
body: <h2>Project Summary</h2>
  <ul>
  <li><p><strong>Goal:</strong> A simple application that connects a client to a server hosted on one computer and allows that client from another computer to send chat messages to everyone on that specified server.</p>
  </li>
  <li><p>Class ClientWindow: Runs an application that prompts the user to enter in a server ID and port. Once entered, it starts the chat program.</p>
  </li>
  </ul>
  <h2>Problem:</h2>
  <p>For some reason unknown to me, the chat program ONLY works when connecting to a server that you've created on your own computer. Other clients from other computers cannot connect to that server.</p>
  <p><strong>Possible reasons for problem:</strong></p>
  <ul>
  <li>I might have incorrectly constructed the server's receiving/sending sockets</li>
  <li>I might have incorrectly constructed the client's receiving/sending sockets</li>
  <li>Something is getting wonky in the packets being sent between client and server</li>
  <li>Somehow IP addresses for the sockets are being defined incorrectly</li>
  </ul>
  <p>Here is the code for the chat program.</p>
  <h3>Start server</h3>
  <p>This class starts the server on the specified port. (12348 in this instance)</p>
  <pre><code>package server;
  
  public class ChatServer {
  
      public static void main(String[] args) {
          // TODO Auto-generated method stub
          
          Server.start(12348);
  
          
      }
  
  }
  </code></pre>
  <h3>Server</h3>
  <p>This is the class that creates the server and listens for client connections and messages.</p>
  <pre><code>package server;
  
  import java.net.DatagramPacket;
  import java.net.DatagramSocket;
  import java.net.InetAddress;
  import java.net.InetSocketAddress;
  import java.util.ArrayList;
  
  public class Server {
  
      private static DatagramSocket socket;
      private static boolean running;
  
      private static int ClientID; // Ensures that no two users have the same client ID
      private static ArrayList&lt;ClientInfo&gt; clients = new ArrayList&lt;ClientInfo&gt;();
  
      public static void start(int port) {
  
          try {
  
              socket = new DatagramSocket(port);
              System.out.println(&quot;Application Starting...&quot;);
              running = true;
              listen();
              System.out.println(&quot;Server started on port: &quot; + port);
  
          } catch (Exception e) {
              System.out.println(&quot;Failed somewhere&quot;);
              e.printStackTrace();
          }
  
      }
  
      private static void broadcast(String message) {
  
          for (ClientInfo info : clients) {
              send(message, info.getAddress(), info.getPort());
          }
  
      }
  
      private static void send(String message, InetAddress address, int port) {
  
          try {
  
              message += &quot;\\e&quot;;
              byte[] data = message.getBytes();
              DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
              socket.send(packet);
              System.out.println(&quot;Sent message to,&quot; + address.getHostAddress() + &quot;:&quot; + port);
  
          } catch (Exception e) {
              e.printStackTrace();
          }
  
      }
  
      private static void listen() {
          
          Thread listenThread = new Thread(&quot;ChatProgram Listener Thread&quot;) {
              
              public void run() {
              
                  try {
                       while(running) {
                           
                           byte[] data = new byte[1024];
                           DatagramPacket packet = new DatagramPacket(data, data.length); 
                           socket.receive(packet);
                           
                           String message = new String(data);
                           //Identify where the end of the message is
                           message = message.substring(0, message.indexOf(&quot;\\e&quot;));
                           
                           //Manage message
                           if(!isCommand(message, packet)) {
                              broadcast(message);
                           }
                          
                       }
                      
                  } catch(Exception e){
                      e.printStackTrace();
                  }
              }
              
          }; listenThread.start();
          
      }
  
      /*
       * SERVER COMMAND LIST 
       * \con:[name] -&gt; Connects client to server 
       * \dis:[id] -&gt; Disconnects client from server
       * 
       * 
       * 
       */
  
      private static boolean isCommand(String message, DatagramPacket packet) {
  
          if (message.startsWith(&quot;\\con:&quot;)) {
              // RUN CONNECTION CODE
  
              String name = message.substring(message.indexOf(&quot;:&quot;) + 1);
              clients.add(new ClientInfo(name, ClientID++, packet.getAddress(), packet.getPort()));
              broadcast(&quot;User &quot; + name + &quot; Connected!&quot;);
  
              return true;
          }
  
          if (message.startsWith(&quot;\\dis:&quot;)) {
              // RUN DISCONNECTION CODE
              
              return true;
          }
  
          return false;
      }
  
      public static void stop() {
  
          running = false;
  
      }
  }
  </code></pre>
  <h3>Start Client</h3>
  <p>Starts the client application.</p>
  <pre><code>package client;
  
  import java.awt.EventQueue;
  import java.awt.Frame;
  
  import javax.swing.JFrame;
  import javax.swing.JOptionPane;
  import javax.swing.UIManager;
  import java.awt.BorderLayout;
  import java.awt.Color;
  import javax.swing.JScrollPane;
  import javax.swing.JTextArea;
  import javax.swing.JButton;
  import javax.swing.JPanel;
  import javax.swing.JTextField;
  import java.awt.FlowLayout;
  import java.awt.event.ActionListener;
  import java.net.InetAddress;
  import java.net.UnknownHostException;
  import java.awt.event.ActionEvent;
  
  public class ClientWindow {
  
      private JFrame frmChatProgram;
      private JTextField textField;
      private static JTextArea textArea = new JTextArea();
      private Client client;
  
      public static void main(String[] args) {
          EventQueue.invokeLater(new Runnable() {
              public void run() {
                  try {
  
                      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                      ClientWindow window = new ClientWindow();
                      window.frmChatProgram.setVisible(true);
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
              }
          });
      }
  
      
      public ClientWindow() throws UnknownHostException {
          initialize();
          String name = JOptionPane.showInputDialog(&quot;Enter name:&quot;);
          String servIp = JOptionPane.showInputDialog(&quot;Enter server IP address:&quot;);
          String port = JOptionPane.showInputDialog(&quot;Enter server port:&quot;);
          
          int parsedPort = Integer.parseInt(port);
          
          //InetAddress inetAddress = InetAddress.getLocalHost();
          
          client = new Client(name, servIp, parsedPort);
      }
  
      private void initialize() {
          
          
          frmChatProgram = new JFrame();
          frmChatProgram.setResizable(false);
          frmChatProgram.setTitle(&quot;Chat Program&quot;);
          frmChatProgram.setBounds(100, 100, 620, 446);
          frmChatProgram.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frmChatProgram.setBackground(Color.WHITE);
          frmChatProgram.getContentPane().setBackground(Color.DARK_GRAY);
          frmChatProgram.getContentPane().setLayout(new BorderLayout(0, 0));
          textArea.setForeground(Color.WHITE);
          
          
          textArea.setBackground(Color.DARK_GRAY);
          JScrollPane scrollPane = new JScrollPane(textArea);
          frmChatProgram.getContentPane().add(scrollPane, BorderLayout.CENTER);
          
          JPanel panel = new JPanel();
          panel.setBackground(Color.GRAY);
          frmChatProgram.getContentPane().add(panel, BorderLayout.SOUTH);
          panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
          
          textField = new JTextField();
          textField.setBackground(Color.WHITE);
          panel.add(textField);
          textField.setColumns(40);
          
          JButton btnNewButton = new JButton(&quot;Send&quot;);
          btnNewButton.addActionListener(e -&gt;{
              
              if (!textField.getText().equals(&quot;&quot;)) {
                  
                  client.send(textField.getText());
                  textField.setText(&quot;&quot;);
                  
              }
              
              
          });
          panel.add(btnNewButton);
          
          frmChatProgram.setLocationRelativeTo(null);
          
      }
      
      public static void printToConsole(String message) {
          
          textArea.setText(textArea.getText() + message + &quot;\n&quot;);
          
      }
  
  }
  </code></pre>
  <h3>Client</h3>
  <p>Creates a client connection and listener for that client</p>
  <pre><code>
  import java.net.DatagramPacket;
  import java.net.DatagramSocket;
  import java.net.InetAddress;
  import java.net.InetSocketAddress;
  
  import server.ClientInfo;
  
  public class Client {
  
      private DatagramSocket socket;
      private InetAddress address;
      private int port;
      private boolean running;
      private String name;
      
      public Client(String name, String address, int port) {
          try {
              this.name = name;
              this.address = InetAddress.getByName(address);
              this.port = port;
              socket = new DatagramSocket();
              socket.connect(this.address, port);
              
              running = true;
              listen();
              send(&quot;\\con:&quot; + name);
  
              
          } catch (Exception e) {
              e.printStackTrace();
          }
  
      }
  
      public void send(String message) {
  
          try {
              
              if (!message.startsWith(&quot;\\&quot;)) {
              message = name+&quot;: &quot;+message;
                  
                  
              }
  
              message += &quot;\\e&quot;;
              byte[] data = message.getBytes();
              DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
              socket.send(packet);
              System.out.println(&quot;Sent message to,&quot; + address.getHostAddress() + &quot;:&quot; + port);
  
          } catch (Exception e) {
              e.printStackTrace();
          }
  
      }
  
      private void listen() {
  
          Thread listenThread = new Thread(&quot;ChatProgram Listener Thread&quot;) {
  
              public void run() {
  
                  try {
                      while (running) {
  
                          byte[] data = new byte[1024];
                          DatagramPacket packet = new DatagramPacket(data, data.length);
                          socket.receive(packet);
  
                          String message = new String(data);
                          // Identify where the end of the message is
                          message = message.substring(0, message.indexOf(&quot;\\e&quot;));
  
                          // Manage message
                          if (!isCommand(message, packet)) {
                              
                              ClientWindow.printToConsole(message);
                              
                          }
  
                      }
  
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
              }
  
          }; listenThread.start();
  
      }
  
      private static boolean isCommand(String message, DatagramPacket packet) {
  
          if (message.startsWith(&quot;\\con:&quot;)) {
              // RUN CONNECTION CODE
  
              return true;
          }
  
          if (message.startsWith(&quot;\\dis:&quot;)) {
              // RUN DISCONNECTION CODE
  
              return true;
          }
  
          return false;
      }
      
      
      
  
  }
  </code></pre>