Results 1 to 3 of 3

Thread: Socket

  1. #1
    vortex is offline Member
    Join Date
    Dec 2007
    Posts
    5
    Rep Power
    0

    Default Socket

    I was experimenting with sockets in java, but i keep getting an exception: java.net.socketexception socket closed...Although i never closed the socket...
    Code:

    ====Server===

    BufferedReader in;
    PrintWriter out;
    try
    {
    ServerSocket listenSocket = new ServerSocket(1331);
    Socket clientSocket = listenSocket.accept();
    in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    out = new PrintWriter(clientSocket.getOutputStream());
    String data = in.readLine();
    System.out.println("Got Data: "+data);
    out.write("Server Received: "+data);
    out.close();
    listenSocket.close();
    }
    catch(IOException e)
    {
    e.printStackTrace();
    }


    ===Client===

    Socket s = null;
    BufferedReader in;
    BufferedWriter out;
    try
    {
    s = new Socket("localhost",1331);
    in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
    out.write("Data From Client Here...");
    out.close();
    String data = in.readLine();
    System.out.println("Data Recieved From Server: "+ data) ;
    s.close();
    }
    catch (Exception e)
    {
    e.printStackTrace();
    }



    As u can see, the code does nothing fancy..the server recieved a string and sends back a confirmation...The server works fine thats for sure, but the problem is with the client, i know that the client freezes when it reachers the line "String data = in.readLine()"

    Any help would be appreciated...
    Thanks...

  2. #2
    farooqza is offline Member
    Join Date
    May 2008
    Posts
    3
    Rep Power
    0

    Default i am a newbie

    when u close the stream the socket associated with is also get closed.
    so remove out.close and write it below ur readline.

  3. #3
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    19

Similar Threads

  1. How to handle socket Exception
    By mayank0512 in forum Networking
    Replies: 14
    Last Post: 12-21-2010, 11:31 PM
  2. Programming Socket Question
    By paul in forum Networking
    Replies: 1
    Last Post: 07-30-2007, 07:26 PM
  3. XML through a socket
    By Heather in forum XML
    Replies: 2
    Last Post: 07-04-2007, 09:31 AM
  4. send files through socket
    By bbq in forum Advanced Java
    Replies: 1
    Last Post: 06-05-2007, 02:08 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •