Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 18 of 18

Thread: Socket closed Exception being thrown.. please help

  1. #1
    Junior Member
    Join Date
    Feb 2014
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Socket closed Exception being thrown.. please help

    I have been working with socket programming. I was trying to develop a two way communication from server to client. The data is being received when sent from server to client but there is a problem when I am sending from client to server.

    I am getting an error as "Socket is closed" pointing to the line where I have created a BufferedReader. I have simplified some part of my code to be very specific.

    Kindly find the code attached.


    import java.io.*;
    import java.net.*;
    import java.util.*;
     
    public class Server
    {
     
       public static void main(String args[])
       {
         String id="policeone";
         int hashcodeid=0;
         try
            {
               ServerSocket srvr=new ServerSocket(1234);
               Socket client=srvr.accept();
               System.out.println("Connected to a client");
     
               PrintWriter out=new PrintWriter(client.getOutputStream(),true);
     
             // code to perfrom operations..
             out.print(id+" ");
             out.print(hashcodeid+" ");
             //out.print(x);
             out.print(message1+" ");
     
     
             //sending data to client working... no problem.
     
     
     
     
    // reading data form client... throwing exception.. "Socket is closed"   
     
     BufferedReader fromserver=new BufferedReader(new InputStreamReader(client.getInputStream()));
                while(!fromserver.ready()){}
     
    String nowstring=fromserver.readLine();
    System.out.println("Received from client    "+nowstring);
     
     
             }
     
    catch(Exception e)
    {
      e.printStackTrace();
    }
        }
    }

    import java.io.*;
    import java.net.*;
    import java.util.*;
     
    public class Client
    {
    public static void main(String args[])
    {
    try{
            String id="vehicle1";
            String idstring,hash,allstring;
            int hashcodeid2=0;
             Socket skt = new Socket("localhost", 1234);
             BufferedReader in = new BufferedReader(new
             InputStreamReader(skt.getInputStream()));
     
     
     
             System.out.print("Received string: '");
     
           while (!in.ready()) {}
     
           //code to read and manipulate data from server
     
     
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     
     
    PrintWriter toserver=new PrintWriter(skt.getOutputStream(),true);
     
     
    toserver.print("helo");
     
    //no problem in client.. server throwing exception at this point.   
     
       }
    catch(Exception e)
    {
      e.printStackTrace();
     }
    }
    }

    error::

    Receiving string from client: 'java.net.SocketException: Socket is closed
    at java.net.Socket.getInputStream(Socket.java:872)
    at Server.main(Server.java:51)


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Socket closed Exception being thrown.. please help

    Please edit your post and wrap your code with code tags:
    [code=java]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.

    Please copy the full text of the error message and paste it here.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Feb 2014
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Socket closed Exception being thrown.. please help

    plz help me sir....

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Socket closed Exception being thrown.. please help

    The posted code does not compile without errors. Please fix the errors.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Feb 2014
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Socket closed Exception being thrown.. please help

    This is original code...

    import java.io.*;
    import java.net.*;
    import java.util.*;
     
    public class Client
    {
    public static void main(String args[])
    {
    try{
            String id="vehicle1";
            String idstring,hash,allstring;
            int hashcodeid2=0;
             Socket skt = new Socket("localhost", 1234);
             BufferedReader in = new BufferedReader(new
             InputStreamReader(skt.getInputStream()));
     
     
     
             System.out.print("Received string: '");
     
           while (!in.ready()) {}
     
              allstring=in.readLine();
          System.out.println("Received               "+allstring); 
         String delims=new String(" ");
         String tokens[]=allstring.split(delims);
     
           for(int i=0;i<tokens.length;i++)
         System.out.println("\nToken number   "+i+1+":"+tokens[i]);  
        int hashid=Integer.parseInt(tokens[1]);
        int message1=Integer.parseInt(tokens[2]);
       System.out.println("Random Number:"+ (hashid^message1));
     
        System.out.println("\n  client sending::");
     
     
     
        in.close();
       }
    catch(Exception e)
    {
      e.printStackTrace();
     }
    }
    }

    server
    import java.io.*;
    import java.net.*;
    import java.util.*;
     
    public class Server
    {
     
       public static void main(String args[])
       {
         String id="policeone";
         int hashcodeid=0;
         try
            {
               ServerSocket srvr=new ServerSocket(1234);
               Socket client=srvr.accept();
               System.out.println("Connected to a client");
     
               PrintWriter out=new PrintWriter(client.getOutputStream(),true);
     
               for(int i=0;i<id.length();i++) 
    	{
             		hashcodeid = 31*hashcodeid + id.charAt(i);
    	}
                   Random random = new Random ();
             int x = 100 + (int)(Math.random()*200);
     
             int message1=hashcodeid^x;
     
             System.out.println("Sending  id string: '" +id  + "'\n");
             System.out.println("Sending  hashcode of id  : '" +hashcodeid  + "'\n");
             System.out.println("Sending  random number: '" +x  + "'\n");
             System.out.println("Sending  message1: '" +message1  + "'\n");
     
             out.print(id+" ");
             out.print(hashcodeid+" ");
             //out.print(x);
             out.print(message1+" ");
     
     
     
     
       out.close();
     
     
             }
     
    catch(Exception e)
    {
      e.printStackTrace();
    }
        }
    }


    --- Update ---

    my problem is sending data from client to server....

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Socket closed Exception being thrown.. please help

    Please post the program's output and add some comments saying what is wrong with it and show what the output should be.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Feb 2014
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Socket closed Exception being thrown.. please help

    client side

    C:\Users\ADITYA\Desktop\project in java\half>java Client
    Received string: 'Received policeone -226259832 -226259891

    Token number 01:policeone

    Token number 11:-226259832

    Token number 21:-226259891
    Random Number:197

    client sending::

    C:\Users\ADITYA\Desktop\project in java\half>

  8. #8
    Junior Member
    Join Date
    Feb 2014
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Socket closed Exception being thrown.. please help

    server side::

    server.jpg

  9. #9
    Junior Member
    Join Date
    Feb 2014
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Socket closed Exception being thrown.. please help

    client sending the hello message... server should accept the hello msg and display the message

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Socket closed Exception being thrown.. please help

    I do not see anywhere in the client code where "hello" is being sent. Did you post the correct code for the client?

    Please don't post images. Copy the contents of the console for the server and paste that.

    Can you add some comments saying what is wrong with it?
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Feb 2014
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Socket closed Exception being thrown.. please help

    Sorry for posting the wrong code..

    Here is the current version with the problem. The Socket Exception is not being thrown here, but the communication is not happening.




    import java.io.*;
    import java.net.*;
    import java.util.*;
     
    public class Server
    {
     
       public static void main(String args[])
       {
         String id="policeone";
         int hashcodeid=0;
         try
            {
               ServerSocket srvr=new ServerSocket(1234);
               Socket client=srvr.accept();
               System.out.println("Connected to a client");
     
               PrintWriter out=new PrintWriter(client.getOutputStream(),true);
     
               for(int i=0;i<id.length();i++) 
        {
                    hashcodeid = 31*hashcodeid + id.charAt(i);
        }
                   Random random = new Random ();
             int x = 100 + (int)(Math.random()*200);
     
             int message1=hashcodeid^x;
     
             System.out.println("Sending  id string: '" +id  + "'\n");
             System.out.println("Sending  hashcode of id  : '" +hashcodeid  + "'\n");
             System.out.println("Sending  random number: '" +x  + "'\n");
             System.out.println("Sending  message1: '" +message1  + "'\n");
     
             out.print(id+" ");
             out.print(hashcodeid+" ");
             //out.print(x);
             out.print(message1+" ");
     
     
     
     
     
     
     BufferedReader fromserver=new BufferedReader(new InputStreamReader(client.getInputStream()));
                while(!fromserver.ready()){}
     
    String nowstring=fromserver.readLine();
    System.out.println("Received from client    "+nowstring);
     
     
             }
     
    catch(Exception e)
    {
      e.printStackTrace();
    }
        }
    }

    import java.io.*;
    import java.net.*;
    import java.util.*;
     
    public class Client
    {
    public static void main(String args[])
    {
    try{
            String id="vehicle1";
            String idstring,hash,allstring;
            int hashcodeid2=0;
             Socket skt = new Socket("localhost", 1234);
             BufferedReader in = new BufferedReader(new
             InputStreamReader(skt.getInputStream()));
     
     
     
             System.out.print("Received string: '");
     
           while (!in.ready()) {}
     
              allstring=in.readLine();
          System.out.println("Received               "+allstring); 
         String delims=new String(" ");
         String tokens[]=allstring.split(delims);
     
           for(int i=0;i<tokens.length;i++)
         System.out.println("\nToken number   "+i+1+":"+tokens[i]);  
        int hashid=Integer.parseInt(tokens[1]);
        int message1=Integer.parseInt(tokens[2]);
       System.out.println("Random Number:"+ (hashid^message1));
     
        System.out.println("\n  client sending::");
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
      String myinput;
     
     
    PrintWriter toserver=new PrintWriter(skt.getOutputStream(),true);
    /*do
     {
       myinput=br.readLine(); 
      System.out.println("You entered       "+myinput);
      System.out.println("Sending       "+myinput+" to server");
      toserver.print(myinput);
     
    }while(!(myinput.equals("n"))); */
     
    toserver.print("helo");
     
     
     
       }
    catch(Exception e)
    {
      e.printStackTrace();
     }
    }
    }

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Socket closed Exception being thrown.. please help

    The code in post #5 worked some. what is different from post#11?

    --- Update ---

    A suggestion for testing:
    Get rid of all this,
    Sending id string: 'policeone'
    Sending hashcode of id : '-226259832'
    Sending random number: '178'
    Sending message1: '-226259910'


    Token number 01:policeone

    Token number 11:-226259832

    Token number 21:-226259910
    do a simple test of sending small strings only until that works.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Feb 2014
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Socket closed Exception being thrown.. please help

    Thank you so much. i have reduced the code as you suggested..but still i am having the problem. could you rectify it sir???
    import java.lang.*;
    import java.io.*;
    import java.net.*;
     
    class Client1 {
       public static void main(String args[]) {
          String data1="hello";
          try {
             Socket skt = new Socket("localhost", 1234);
             BufferedReader in = new BufferedReader(new
                InputStreamReader(skt.getInputStream()));
             System.out.print("Received string: '");
     
             while (!in.ready()) {}
             System.out.println(in.readLine()); // Read one line and output it
     
             System.out.print("'\n");
     
             PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
              System.out.print("Sending string: '" + data1 + "'\n");
             out.print(data1);
             out.close();
             in.close();
          }
          catch(Exception e) {
             System.out.print("Whoops! It didn't work!\n");
          }
       }
    }

    import java.lang.*;
    import java.io.*;
    import java.net.*;
     
    class Server1 {
       public static void main(String args[]) {
          String data = "Toobie ornaught toobie";
          try {
             ServerSocket srvr = new ServerSocket(1234);
             Socket skt = srvr.accept();
             System.out.print("Server has connected!\n");
             PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
             System.out.print("Sending string: '" + data + "'\n");
             out.print(data);
             out.close();
     
             BufferedReader in = new BufferedReader(new
                InputStreamReader(skt.getInputStream()));
             System.out.print("Received string: '");
     
              in.close();
             skt.close();
             srvr.close();
          }
          catch(Exception e) {
             System.out.print("Whoops! It didn't work!\n");
          }
       }
    }

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Socket closed Exception being thrown.. please help

    l i am having the problem.
    Which problem?
    Please copy the full text of the messages that show the problem and paste them here.

    What do you expect the code to do? List the steps in time sequence of what should happen in the two classes.
    The server does this
    the client does that
    etc
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Junior Member
    Join Date
    Feb 2014
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Socket closed Exception being thrown.. please help

    C:\Users\ADITYA\Desktop\example>java Server1
    Server has connected!
    Sending string: 'Toobie ornaught toobie'
    Whoops! It didn't work!


    C:\Users\ADITYA\Desktop\example>javac Client1.java

    C:\Users\ADITYA\Desktop\example>java Client1
    Received string: 'Toobie ornaught toobie
    '
    Sending string: 'hello'


    The client is sending hello to server, but it is not geting received on the server side.. the exception is being thrown there.. as "Socket is closed"

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Socket closed Exception being thrown.. please help

    the exception is being thrown there.. as "Socket is closed"
    You left that off of the output that you posted. You need to post ALL of the contents of the console from when you test the code.

    Whoops! It didn't work!
    That needs to be the output from the printStackTrace() method



    What do you expect the code to do?
    Make a List of the steps in time sequence of what should happen in the two classes. Something list this:
    The server does this
    the client does that
    etc
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Junior Member
    Join Date
    Feb 2014
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Socket closed Exception being thrown.. please help

    please sir,
    i want the server receives the hello msg...

    The output clearly shows client sending hello msg to server,but server is not taking the hello msg and throws exception....
    I know "whoops It didnt work " is the output of printstacktrace().......

    1)the server sends
    toobie or naught toobie

    the client receives
    toobie or naught toobie

    2)the client sends
    hello

    the server receives
    whoops it didnt work

    --- Update ---

    i have replace "whoops it didnt work" with printStackTrace().... it shows the below error

    Server has connected!
    Sending string: 'Toobie ornaught toobie'
    java.net.SocketException: Socket is closed
    at java.net.Socket.getInputStream(Socket.java:872)
    at Server1.main(Server1.java:17)

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Socket closed Exception being thrown.. please help

    The list of steps leaves out the creation of the sockets. The server can't send anything until after it creates a server socket and the client connects to that socket.

    Look at the API doc for the readLine() method. It says that it reads a "line" and defines a "line" as: A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Java Socket Exception Socket Closed
    By premkumar.rj in forum What's Wrong With My Code?
    Replies: 5
    Last Post: February 8th, 2014, 01:12 AM
  2. socket closed
    By tyler_long_sim in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 21st, 2013, 05:52 PM
  3. getting closed server socket in client thread
    By shanalikhan in forum What's Wrong With My Code?
    Replies: 8
    Last Post: January 13th, 2013, 06:18 PM
  4. How to detect if Socket is closed by remote peer?
    By anis_huq in forum Java Networking
    Replies: 1
    Last Post: July 13th, 2012, 09:36 AM
  5. Exception Thrown
    By Frame in forum What's Wrong With My Code?
    Replies: 1
    Last Post: October 29th, 2011, 11:14 PM