-1

So, i am trying to create a Client Server chat program. Since, i don't have an external server so my client and server will be hosted in my computer. Now, i was following online tutorials and created the Server side of the chat program but then i get an error while i test the Server side of the program. When i create the server socket, what port number should i put if i am using my computer. I used a random number and i get the following errors:- Can someone please help me to fix the error or suggest me what should i do? Thanks

enter image description here

This is my Server class:-

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.*;
import java.io.*;
import java.awt.*;

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




public class Server extends JFrame {

    private JTextField usertext;
    private JTextArea  chatwindow;
    private ObjectOutputStream output;
    private ObjectInputStream input;

    private ServerSocket server;
    private Socket connection;


    public Server()
    {
        super("Missy's Instant Messenger");//This sets the title of the messenger window
        usertext = new JTextField(); //this is for creating the textfield where the user will enter data
        usertext.setEditable(false);//this is set to false such that the user can only send message if he is connected to someone 
        usertext.addActionListener( //this activity is for sending the message when the user clicks on enter
                new ActionListener(){
            public void actionPerformed(ActionEvent event){
                sendMessage(event.getActionCommand());
                usertext.setText(" ");

            }

        /*  private void sendMessage(String string) {
                // TODO Auto-generated method stub

            }*/
        });

         add(usertext,BorderLayout.NORTH); 
         chatwindow = new JTextArea();
         add(new JScrollPane(chatwindow));
         setSize(500,500);




    }


   public void startrunning(){

       try {
        server = new ServerSocket(6800,100);
        //6789 is the port number and 100 is the number of people that can wait in the queue to connect to the server

        while(true)
        {
            try{
                waitforConnection();//this is to connect to the server
                setupStreams();//setting up the input and output streams to send and receive messages
                whilechatting();//this is allow to send messages using the input and output streams



            }catch (Exception e)
            {
                showMessage("Connection has ended");//this will be displayed when the connection is ended by the server

            }finally{
                closecrap(); //close all the streams and sockets 
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

   }

   private void waitforConnection() throws IOException
   {
       showMessage("waiting for someone to connect.....");
       connection = server.accept(); //this will connect the server and the client
       showMessage("Now connected to "+connection.getInetAddress().getHostName());

   }

   private void setupStreams() throws IOException
   {
       output = new ObjectOutputStream(connection.getOutputStream());
       output.flush();

       input = new ObjectInputStream(connection.getInputStream());
       showMessage("Your streams are now set up......");
   }


   private void whilechatting() throws IOException
   {
       String message = "You are now connected";
       sendMessage(message);
       abletotype(true);

       do{

           try{
               message = (String)input.readObject();
               showMessage("\n" +message);

           }catch(ClassNotFoundException e)
           {
               showMessage("wtf is that");
           }




       }while(!message.equals("CLIENT END"));

   }

   private void showMessage(final String a)

   {
       SwingUtilities.invokeLater(

               new Runnable(){

                   public void run(){
                       chatwindow.append(a);
                   }
               }

               );
     //  System.out.println(a);
   }

   public void closecrap()
   {
       showMessage("\n Connections closing .....");
       abletotype(false);
       try{
           output.close();
           input.close();
           connection.close();

       }catch(IOException ioException)
       {
           ioException.printStackTrace();
       }
   }

   public void sendMessage(String message)
   {
       try{
           output.writeObject("SERVER - "+message);//this is where you put the message in the output stream
           output.flush(); //flush out the junk if there is any left
           showMessage("\nSERVER -"+message); //show Message in the chat window

       }catch(Exception e)
       {
           chatwindow.append("\n ERROR sending the message dude");
       }
   }



   private void abletotype(final Boolean t)
   {
       SwingUtilities.invokeLater(

               new Runnable(){

                   public void run(){
                       usertext.setEditable(t);
                   }
               }

               );
   }
}

Servertest class:-

 import javax.swing.*;
public class ServerTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Server st = new Server();
        st.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        st.startrunning();


    }

}

References:- ThenewBoston.com

Missy Zewdie
  • 231
  • 2
  • 9
  • 17
  • "Address already in use: JVM_Bind" Usualy says the address is already used, are you sure you aren't running the program twice by a accident? – Ferrybig Sep 01 '15 at 13:15
  • @ferrybig:- I restarted eclipse and ran it again. Same error and it points to the line where i created the server socket. Probably the port number is already in use. – Missy Zewdie Sep 01 '15 at 13:18
  • you don't close your `ServerSocket` in your code. Run `netstat` (windows cmd) to check used port – flafoux Sep 01 '15 at 13:19
  • @flafoux:- I thought that connection.close() would close the sockets ....or do i need to do it separetely.? – Missy Zewdie Sep 01 '15 at 13:22
  • @flafoux- I edited the port number to port number - 7020....and the error disappears but then i don't even see the GUI....what could be the issue? – Missy Zewdie Sep 01 '15 at 13:25
  • Hint: Separate user interface from functionality. A server really doesn't need to have a GUI. Anyway, please avoid questions that are "moving targets" - when you find one problem you ask about another. – RealSkeptic Sep 01 '15 at 13:31

1 Answers1

0

I am going to summarize what has been said in some of the comments, and add my own thoughts.

First and foremost, the port is likely already in use. Its probably not in use by your program from what you said, however some other program is using it or has it reserved. As far as I know there is no official use for port 100, so it is likely just another program you have installed on your machine. Also from the comments it seems you have fixed this by swapping to a different port.

Connection.close() should work fine for closing the connection. For more information check out this link: How can I close the socket in a proper way?

As far as your most recent comment goes - if the program is running but the UI is not appearing, you likely have another issue with the code unrelated to your posted issue. I might suggest attempting to debug it on your own from here now that the server is starting without the JVM_BIND error and see what you come up with.

Community
  • 1
  • 1
Sh4d0wsPlyr
  • 948
  • 12
  • 28