Socket.getInputStream hangs

I have a simple client/server app, and the client hangs when I try to get the input stream coming out of the server. I have the following code on the server:
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
port = 49152;
server = new ServerSocket(port, 0, InetAddress.getLocalHost());
sock = server.accept();
oos = new ObjectOutputStream(sock.getOutputStream());
ois = new ObjectInputStream(sock.getInputStream());
String inMsg = (String) ois.readObject();
oos.writeObject(outMsg);
oos.close();
ois.close();
sock.close();And I try to invoke it with this code on the client:
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
String inMsg = "";
int port = 49152;
try {
     Socket sock = new Socket(InetAddress.getLocalHost(), port);
     oos = new ObjectOutputStream(sock.getOutputStream());
     ois = new ObjectInputStream(sock.getInputStream());//the code hangs here
     oos.writeObject(outMsg);
     inMsg = (String) ois.readObject();
        oos.close();
     ois.close();
     sock.close();
} catch (Exception e) {
     return "";
return inMsg;
     The code hangs where indicated in the comments. Can someone tell me what I'm doing wrong?
Edited by: MidnightJava on Apr 10, 2008 4:55 AM

Can you please explain the rationale for your suggestion? What sort of problem is it addressingThe constructor for ObjectOutputStream writes a header to the stream. The constructor for ObjectInputStream reads it. Try constructing them in the opposite order at both ends and you will see a lovely deadlock. The flush() is required if there is a BufferedOutputStream under the ObjectOutputStream.
is it a good idea to do it always when creating streams from a socket?It's essential when dealing with object streams. Other streams, no.

Similar Messages

  • Socket.getOutputStream must precede the socket.getInputStream?!? Why?

    This is server code.......
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class DateServer extends Thread {
       private ServerSocket dateServer;
       public static void main(String argv[]) throws Exception {
         new DateServer();
       public DateServer() throws Exception {
         dateServer = new ServerSocket(3000);
         System.out.println("Server listening on port 3000.");
         this.start();
       public void run() {
         while(true) {
           try {
            System.out.println("Waiting for connections.");
            Socket client = dateServer.accept();
            System.out.println("Accepted a connection from: "+
    client.getInetAddress());
            Connect c = new Connect(client);
           } catch(Exception e) {}
    class Connect extends Thread {
       private Socket client = null;
       private ObjectInputStream ois = null;
       private ObjectOutputStream oos = null;
       public Connect() {}
       public Connect(Socket clientSocket) {
         client = clientSocket;
         try {
          ois = new ObjectInputStream(client.getInputStream());
          oos = new ObjectOutputStream(client.getOutputStream());
         } catch(Exception e1) {
             try {
                client.close();
             }catch(Exception e) {
               System.out.println(e.getMessage());
             return;
         this.start();
       public void run() {
          try {
             oos.writeObject(new Date());
             oos.flush();
             // close streams and connections
             ois.close();
             oos.close();
             client.close();
          } catch(Exception e) {}
    }This is client code....
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class DateClient {
       public static void main(String argv[]) {
          ObjectOutputStream oos = null;
          ObjectInputStream ois = null;
          Socket socket = null;
          Date date = null;
          try {
            // open a socket connection
            socket = new Socket("127.0.0.1", 3000);
            // open I/O streams for objects
            oos = new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());
              System.out.println( "BAU!" );
            // read an object from the server
            date = (Date) ois.readObject();
            System.out.print("The date is: " + date);
            oos.close();
            ois.close();
          } catch(Exception e) {
            System.out.println(e.getMessage());
    }OK.
    Those work just fine. Now if you put socket.getInputStream before the socket.getOutputStream then it hangs!
    Any ideea why this happens and why is not documented... I just lost tow hour tring to figure it out why my program just hangs. After I have set the order as In the example above all works....
    If anyone knows why please share your knowledge...
    Hope this will save others a lot of lost time.

    The order matters because the ObjectOutputStream constructor writes a stream header and the ObjectInputStream constructor reads the header.
    If both ends of the conversation do "new ObjectInputStream()" they both forever wait for the other end to write the header. So one end needs to create the output stream first and the input stream second, and the other end in the other order (or do them in different threads.)
    If it isn't documented it should be IMHO. Re-check the javadocs; if it isn't mentioned file a bug report to Sun. There is a bug parade link on http://java.sun.com/ somewhere.

  • Socket reading: hanging when using java, but OK when using javaw

    Tested and experienced on:
    Windows 2000 Workstation, Windows XP SP1
    jdk build 1.4.1_02-b06, build 1.4.2_04-b04
    My app is a GUI application. I am creating a socket like this:
    Socket socket = new Socket();
    socket.connect(new InetSocketAddress(proxy_host, Integer.parseInt(proxy_port)), 8000);
    BufferedReader in =
      new BufferedReader(
      new InputStreamReader(socket.getInputStream()));
    PrintWriter out =
      new PrintWriter(
       new BufferedWriter(
        new OutputStreamWriter(socket.getOutputStream())),true);
    String request = "GET url HTTP/1.1\r\n" +
                     "Accept: *\r\n" +
                     "Host: host\r\n" +
                     "Cookie: " + sessionCookie + "\r\n" +
                     "User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0; YComp 5.0.0.0)" + "\r\n" +
                     "Content-type: application/x-www-form-urlencoded" + "\r\n\r\n";
    out.print(request);
    out.flush();
    String str = "";
    while((str = in.readLine()) != null)
    socket.close();I am reading a HTML document from server. If I use the call
    java -jar MyJar.jar
    the reading starts hanging by reading the list line of the document. By call
    javaw -jar MyJar.jar
    all is fine. What could be the problem. I am really perplexed!

    Sounds like perhaps a timing issue. But a bigger issue is why aren't you simply using the higher-level java.net.URL, HttpURLConnection classes? You're reinventing the wheel here by writing low-level socket calls with HTTP protocol strings.

  • Multiple references to socket.getInputStream()

    I am writing a simple client server game and am trying to pass both input and Objects over the socket stream.
    Is it possible to have:
    BufferedReader ins = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());Or will this cause problems? I am positive of the order of input and objects, so there is no ambiguity on whether to read from ois or ins, but will there be some bad-mojo there anyway?

    Thanks. I've read alot of posts about this and this is the first time I've seen the deprecated readLine solution. Doesn't this seem to be a fairly significant problem? Is BufferedReader supposed to be accepting serialized objects anytime soon?
    I suppose that I could simply close the socket and reestablish a connection using an ObjectInputStream, but what do commercial developers do? Do they just rely on passing String objects or is BufferedReader preferred?

  • Non blocking socket: GUI hangs

    Hello,
    i have made a swing based GUI. It sends a request to the local server and the server keep sending response to it.
    Basically request is sent once, but response is in the form of stream.
    But my problem is that GUI hangs after getting the response from the server, because the socket is still getting the reponse. how can I get rid of this problem?
    regards,
    Saurabh

    Hi Saurabh,
    Tom is right, threads are the way. There is even a dedicated swing api (as far as i can remember), which lets you exec. lengthy tasks in a tread and be notified (the gui) when the task quits.
    Regards
    Gregor

  • Socket.getInputStream() doesn't initialise empty

    I would appreciate any help with the following:
    When using a stream socket to transfer a file from a server to a client, I seem to have trouble with the first byte in the socket input steam.
    I have isolated the code down to the following:
    SERVER CODE
    OutputStream os = sock.getOutputStream();
    int b = 33; // pick an integer to send
    System.out.println("\nFIRST BYTE=" + b); /// here see 33 ok
    os.write(b);
    os.close();
    CLIENT CODE
    InputStream is = sock.getInputStream();
    int b = is.read(); //<<<< here for some reason b = 10????
    System.out.println("\nFIRST BYTE=" + b); /// here display is 10
    I do not get this problem with other inputstreams from System.in (ie. keyboard) or file, only get this problem with the socket inputSteam where first byte is always 10 (I think this is a newline char) , then the following bytes are fine. I am going around in circles trying to figure this one out.
    Note: a work around is to simply read the first byte and discard but this is not explaining the problem.
    Any suggestions?

    Thanks for the replies, I have finally nutted out the problem. For those of you interested . . .
    The fact that that the byte value was 10 (ie linefeed) gave some hints, finally found a stray �\n� was still in inputstream waiting to be read due to an earlier loop error of mine.
    I thought I was instantiating a new inputstream object but in fact was creating and alias for an already created object (containing a left over �\n�).
    Problem solved!
    I have learnt a lot in the 6hrs of pondering this �simple� problem.
    Thanks again

  • Is Socket.getInputStream() expensive?

    Hi,
    I am writing an app. that will communicate frequently with other instances of itself on other machines. Now, in the beginning I am going to create socket connections among all apps on all machines. I was thinking of storing the resulting socket variable in a HashMap keyed by machine name. But, then everytime I have to write a message to another machine I would have to do this:
    Socket sock = machine2socket.get(machineName);
    ObjectOutputStream oos= new ObjectOutputStream(sock.getInputStream());
    oos.writeObject(...);I am wondering if it would be more efficient to create the ObjectOutputStream once during initialization and then retrieve that from a HashMap as well.
    Any thoughts?

    No, it comes free with Java... :-)
    First, presumably, the better way would be to create an object to hold the socket, and when you create that object, you pass it the socket to the constructor and in that create your input and output stream wrappers (Object stream, BufferedReaders, whatever), so you aren't creating new ones all the time.
    That being said, if you are talking about relatively few clients, I suppose this architecture could be okay. But the more clients running and talking to each other, the more cross connections you have. If you are going to broadcast the same objects to all clients, it might be better to have 1 server that all clients connect to. Then you send objects to the server and let it resend to all other clients. You can have some kinda protocol to send objects to specific clients, get a client list, notification of client connect/disconnect, various other things. This way you have 1 socket connection per client to 1 server, instead of X connections to each of X clients.
    Further, the clients have to know where all the other clients are or find them somehow (port scan, for example). A common server is going to be easier to configure then configuring or auto-discovering other clients.

  • Write to socket hange the process

    Hi, my program uses sockets. All is fine, but when the other side suddenly shut downs, my process
    stays hung into the write system call. According to pStack, my process is also stuck on the
    close system call (Since it noticed that the other side was shut down). What happeded ? did the process entered some deadlock because trying to close a socket that is trying to write to it??
    I can't even receive any terminating signals, when normally I receive them with no problem.
    Please help!!!

    This is what I get, what do you get:
    java -server Loopback1000000 messages in 3004 ms
    1000000 messages in 2752 ms
    1000000 messages in 2706 ms
    1000000 messages in 2728 ms
    import java.io.*;
    import java.net.*;
    public class Loopback
        static final int PORT = 6666;
        public static void main(String args[])
         throws Exception
         new Listener().start();
         Socket socket = new Socket("localhost", PORT);
         DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
         int count = 0;
         long start_time = System.currentTimeMillis();
         while (true) {
             out.writeBytes("hello world");
             out.flush();
             if (++count % 1000000 == 0) {
              long now = System.currentTimeMillis();
              System.out.println("1000000 messages in " + (now - start_time) + " ms");
              start_time = now;
        static class Listener
         extends Thread
         ServerSocket server_socket;
         Listener()
             throws IOException
             server_socket = new ServerSocket(PORT);
         public void run()
             try {
              while (true) {
                  Socket socket = server_socket.accept();
                  InputStream in = socket.getInputStream();
                  byte buf[] = new byte[8192];
                  while (true) {
                   if (in.read(buf) == -1)
                       break;
                  in.close();
                  socket.close();
             } catch (IOException e) {
              System.out.println("error in listener: " + e);
    }

  • Client/Server hang up?

    I'm writing a basic client server program. I created an ArrayList to hold all the sockets of a connection so each client could, hopefully, eventually interact.
    Right now my client is a text field with a text area under it. A user types a command up top and then hits enter and sends that along to the server. However when i send in the message it seems to hang up and never sends back a reply. But what's really odd about it, is that if i close my server window and there by shutting it down the client then outputs exactly what i expected it to if it was working right. So im curious why there's this hangup in my code?
    Server:
    import java.awt.BorderLayout;
    import java.awt.Font;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.ArrayList;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    public class Server extends JFrame{
              private JTextArea jta = new JTextArea();
              private static ArrayList<Socket> clients = new ArrayList<Socket>();
              public Server(){
                   getContentPane().setLayout(new BorderLayout());
                   getContentPane().add(new JScrollPane(jta), BorderLayout.CENTER);
                   jta.setFont( new Font( "Times", Font.BOLD, 20));
                   setSize(500, 300);
                   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   setVisible(true);
                   try{
                        setTitle("Server: " + InetAddress.getLocalHost().getHostName());
                        int clientNo = 1;
                        ServerSocket serverSocket = new ServerSocket(0);
                        jta.append("Port: " + serverSocket.getLocalPort() + "\n");
                        while(true){
                             Socket socket = serverSocket.accept();
                             InetAddress inetAddress = socket.getInetAddress();
                             clients.add(socket);
                             World thread = new World(socket);
                             jta.append("Connected with client :" + clientNo + "\n");
                             thread.start();
                             clientNo++;
                   }catch(IOException ex){
                        System.err.println(ex);
              public static void main(String[] args){
                   new Server();
              public static ArrayList getClients(){
                   return clients;
         }World:
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.Scanner;
    public class World extends Thread {
         private Socket mySocket;
         private int myPort;
         private InetAddress myInetAddress;
         private String myHostName;
         private ArrayList<Socket> theClients;
         public World(Socket newSocket) {
              mySocket = newSocket;
              myPort = mySocket.getPort();
              myInetAddress = mySocket.getInetAddress();
              myHostName = myInetAddress.getHostName();
         public void run() {
              String test;
              Scanner input = null;
              PrintWriter output = null;
              try {
                   String fileName;
                   input = new Scanner(mySocket.getInputStream());
                   output = new PrintWriter(mySocket.getOutputStream(), true);
              }catch(IOException e){
              output.println("Please Enter Command");
              while((test = input.nextLine()) != null){
                   if(test.contains("get clients") ){
                        theClients = Server.getClients();
                        for(int i = 0; i < theClients.size(); i++){
                             output.println(theClients.get(i).getInetAddress().getHostName());
                        output.flush();
                   }else{
                        output.println("not sure");
                        output.flush();
    }Client:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.Scanner;
    import javax.swing.*;
    public class Client extends JFrame implements ActionListener{
         private JTextField jtf;
         private JTextArea jta = new JTextArea();
         private PrintWriter output;
         private Scanner input;
         public Client(String host, int port){
              JPanel p1 = new JPanel();
              p1.setLayout(new BorderLayout());
              p1.add(jtf = new JTextField(10), BorderLayout.CENTER);
              jtf.setHorizontalAlignment(JTextField.RIGHT);
              jtf.setFont(new Font("Times", Font.BOLD, 20));
              jta.setFont(new Font("Times", Font.BOLD, 20));
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(p1, BorderLayout.NORTH);
              getContentPane().add(new JScrollPane(jta), BorderLayout.CENTER);
              jtf.addActionListener(this);
              setSize(500,300);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
              try{
                   setTitle("Client: " + InetAddress.getLocalHost().getHostName());
                   Socket socket = new Socket(host, port);
                   input = new Scanner(socket.getInputStream());
                   output = new PrintWriter(socket.getOutputStream(), true);
                   jta.append(input.nextLine() + "\n");
              }catch(IOException ex){
                   jta.append(ex.toString() + "\n");
         public void actionPerformed(ActionEvent e){
              String nextLine;
              String findFile = jtf.getText().trim();
              ((JTextField)(e.getSource())).setEditable(false);
              if ( e.getSource() instanceof JTextField){
                        jta.append("Getting file: \"" + findFile + "\" \n");
                        output.println(findFile);
                        output.flush();
                        while(input.hasNext()){
                             nextLine = input.nextLine();
                             jta.append(nextLine + "\n");
         public static void main(String[] args){
              int portSend;
              if (args.length != 2){
                   System.out.println("not Enough arguments");
                   System.exit(-1);
              portSend = Integer.parseInt(args[1]);
              new Client(args[0], portSend);
    }

    Don't run networking code in the constructor. Start a separate thread for the accept loop.

  • ObjectInputStream+CipherInputStream hang

    I've started a simple client-server app and had communication working fine untill I tried to add encryption.
    Here's the faulty code with info on object initialization
    // init in and out cipher
    outCipher = Cipher.getInstance(algorithm);
    outCipher.init(Cipher.ENCRYPT_MODE, key);
    inCipher = Cipher.getInstance(algorithm);
    inCipher.init(Cipher.DECRYPT_MODE, key);
    // create ObjectInput/Output stream
    cipherOut = new ObjectOutputStream(
    new CipherOutputStream(socket.getOutputStream(), outCipher));
    cipherIn = new ObjectInputStream( // <--- HANGS HERE
    new CipherInputStream(socket.getInputStream(), inCipher));
    My key is genereated just fine, and the ObjectOutputStream is created ok, it just hangs at cipherIn.
    The only odd part about the output is this, which is outputted twice before each of the inCipher.init's are executed:
    java.io.IOException: Caching not supported for http://www.tgpr.org/LlamaChat/
         at sun.plugin.cache.CachedJarLoader.download(CachedJarLoader.java:323)
         at sun.plugin.cache.CachedJarLoader.load(CachedJarLoader.java:131)
         at sun.plugin.cache.JarCache.get(JarCache.java:177)
         at sun.plugin.net.protocol.jar.CachedJarURLConnection.connect(CachedJarURLConnection.java:71)
         at sun.plugin.net.protocol.jar.CachedJarURLConnection.getJarFile(CachedJarURLConnection.java:56)
         at javax.crypto.SunJCE_e.run(DashoA6275)
         at java.security.AccessController.doPrivileged(Native Method)
         at javax.crypto.SunJCE_d.a(DashoA6275)
         at javax.crypto.SunJCE_d.a(DashoA6275)
         at javax.crypto.SunJCE_d.verify(DashoA6275)
         at javax.crypto.SunJCE_g.a(DashoA6275)
         at javax.crypto.SunJCE_b.a(DashoA6275)
         at javax.crypto.SunJCE_b.a(DashoA6275)
         at javax.crypto.Cipher.getInstance(DashoA6275)
         at ServerConnection.initializeCipher(ServerConnection.java:76)
         at SD_Key.performAction(SD_Key.java:14)
         at ServerConnection.<init>(ServerConnection.java:54)
         at LlamaChat.connect(LlamaChat.java:195)
         at LlamaChat.init(LlamaChat.java:78)
         at sun.applet.AppletPanel.run(AppletPanel.java:341)
         at java.lang.Thread.run(Thread.java:536)
    can anyone help? I think i've tried everyting I can think of and i sure its possible to do this.
    If you need more info to help, I'd be happy to provide :)
    Thanks@
    -Joe

    Ok ... I was able to hack up the code a bit to break up getting the new ObjectInutStream, and it was able to execute the new CipherInputStream, but still hung on the new ObjectInputStream.
    I took this a bit further and was able to transfer data over my Cipher(Input|Output)Stream.
    I also tried different combinations of ordering the input and output and also tried comintations of Buffered(Input|Output)Streams on my other streams, but nothign worked :(
    So ... I'm still in need of assistance.
    Thanks!
    - Joe

  • Socket communication between applet and an AP on simulastor

    Hi!
    I implemented my system under Server/Client model.
    The server is running in a Set-Top-Box simulator, which
    creates a ServerSocket on port 9190.
    The client is an applet and using the following codes to connect to server:
    ==========================================
    Socket socket = new Socket("127.0.0.1", 9190)
    InputStream in = socket.getInputStream();
    OutputStream out = socket.getOutputStream();
    ==========================================
    When I start the applet, no exceptions are thrown,
    and objects socket, in and out are not null.
    But when I was trying to send a string to server,
    ==========================================
    out.write("a string".getBytes());
    ==========================================
    nothing happened. Server didn't get anything.
    What's wrong? How can I solve this?

    First of all "nothing happend" is something you tell the DELL helpdesk.
    This is a developer forum.
    My guess is you are using somthing of a in.readLine() on the server and since the
    client doesn't sent a linebreak it will hang there.
    Or the client gets an AccessControlException that you silently catch and therefore get
    no exception. Allthough the InputStream would be declared in the try block (according
    to posted code) and can not be checked for beeing null in the catch (out of scope).
    Here is some sample code of client and server, try to implement the run method in
    your client and run both appTest and applet on the local machine (http://127.0.0.1).
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class appTest implements Runnable {
         public appTest() {
              new listner().start();
              new Thread(this).start();
         // main program
         public static void main(String argv[]) throws Exception {
              new appTest();
         public void run() {
              // the client
              try {
                   Socket s = new Socket("127.0.0.1", 9190);
                   // if multiple messages are to be sent and received
                   // this is where you start a new thread
                   byte b[];
                   OutputStream out = s.getOutputStream();
                   InputStream in = s.getInputStream();
                   String message = "hello from client";
                   int messageLength = message.getBytes().length;
                   // writing the length of the message
                   out.write(new Integer(messageLength).byteValue());
                   b = message.getBytes();
                   // writing the message
                   out.write(b);
                   // reading the length of the message and setting the byte array to
                   // it
                   b = new byte[in.read()];
                   in.read(b);
                   // receiving the message
                   System.out
                             .println("received massage from server: " + new String(b));
                   out.close();
                   in.close();
              } catch (Exception e) {
                   e.printStackTrace();
         class listner extends Thread {
              public void run() {
                   try {
                        ServerSocket srv = new ServerSocket(9190);
                        while (true) {
                             try {
                                  System.out.println("before accepting a client");
                                  Socket s = srv.accept();
                                  System.out.println("after accepting a client");
                                  // if multiple messages are to be sent and received
                                  // this is where you start a new thread
                                  byte b[];
                                  OutputStream out = s.getOutputStream();
                                  InputStream in = s.getInputStream();
                                  // reading the length of the message and setting the
                                  // byte array to
                                  // it
                                  b = new byte[in.read()];
                                  in.read(b);
                                  // receiving the message
                                  System.out.println("received massage from client:"
                                            + new String(b));
                                  System.out.println("sending message from server:");
                                  String message = "hello from server";
                                  int messageLength = message.getBytes().length;
                                  // writing the length of the message
                                  out.write(new Integer(messageLength).byteValue());
                                  b = message.getBytes();
                                  // writing the message
                                  out.write(b);
                                  out.close();
                                  in.close();
                             } catch (Exception ex) {
                                  ex.printStackTrace();
                   } catch (Exception e) {
                        e.printStackTrace();
    }

  • Server Socket does not read data input stream

    Hi all,
    I am very newbie to Java Network programming with sockets and multi-threading.
    But I am obliged to develop a chat system written in Applets which can be placed on the website and used by visitors who come to my website.
    In order to understand this, I have tested a basic web chat program I downloaded from the Internet which use sockets and multi-threadings. The program work fine, no bugs at all at both compilation and run time. I noticed that all three streams for Client side (i.e. first one is input stream used receiving data from User; the second one is socket input stream used for receiving data from Server socket, and the third is socket output stream used for writing data to server socket) were established. And the same, two socket streams (input & output) for Server side were also connected when running program giving right port number and IP address of the server.
    The problem is both server and client sockets do not read data using the following stream classes:
    1. DataStreamInput: I use input.readUTF() method
    2. or BufferedReader: I use input.readLine() method
    The example of the codes are below:
    private BufferedReader input = null;
    private PrintWriter output = null;
    private Socket socket = null;
    public void open() throws IOException
    {  input = new BufferedReader(new
    InputStreamReader(socket.getInputStream()));
    System.out.println("Server socket input stream was created, and");
    output = new PrintWriter(socket.getOutputStream());
    System.out.println("Server socket output stream was created");
    public void run()
    {  System.out.println("Server Thread " + clientPort + " running.");
    while (true)
    {  try
    System.out.println("Server is reading data from Client, wait...");
    String fromClient = input.readLine();
    System.out.println("Server received a message on " + clientPort + ".");
    catch(IOException ioe)
    {  System.out.println(clientPort + " ERROR reading: " + ioe.getMessage());
    server.remove(clientPort);
    stop();
    The problem is at the line: String fromClient = input.readLine(); in the run() method? What is wrong with the codes above?
    Note: I also try to use original codes which use readUTF() method in DataStreamInput class instead using readLine() in BufferedReader. Both methods dont read data from inputstream socket?
    I very appreciate any help/advice from experienced developers.
    Best regards

    Hi,
    Yes. The readLine() method hangs! After the test, the execuation of the program is stopped at the line of readLine() method; it does not pass it?
    There is no problem with writing to Server socket. After the test, the program pass through flush() method. Here is the code for writing to sever socket within ChatClient (client side socket) class:
    private BufferedReader input = null;
    private PrintWriter           output = null;
    public ChatClient(String serverName, int serverPort)
    {  System.out.println("Establishing connection. Please wait ...");
    try
    {  socket = new Socket(serverName, serverPort);
    System.out.println("Connected: " + socket);
    start();
    catch(UnknownHostException uhe)
    {  System.out.println("Host unknown: " + uhe.getMessage()); }
    catch(IOException ioe)
    {  System.out.println("Unexpected exception: " + ioe.getMessage()); }
    public void start() throws IOException
    {  input   = new BufferedReader (new
                             InputStreamReader(System.in));
    System.out.println("Client User input stream was created,");
    output = new PrintWriter(socket.getOutputStream());
    System.out.println("Client Socket output stream was established, and");
    if (thread == null)
    {  client = new ChatClientThread(this, socket);
    thread = new Thread(this);
    thread.start();
    public void run()
         while (thread != null) {
         String fromUser;
              try{
                   while((fromUser = input.readLine())!= null)
                   System.out.println("Client wasreading a data from User, and");
    output.println(fromUser);
         output.flush();
         System.out.println("Client has written a data to Server");
    catch(IOException ioe)
    {  System.out.println("Sending to server error: " + ioe.getMessage());
    stop();
    etc.
    Here is a piece of codes for reading data from the Client Socket in the ChatServer Class (Server Side socket):
    public void run()
    {  System.out.println("Server Thread " + clientPort + " running.");
    while (true)
    {  try
    {  //server.handle(clientPort, input.readLine());
    System.out.println("Server is reading data from Client, wait...");
    String fromUser = input.readLine();
    //while((fromUser = input.readLine()) != null)
         System.out.println("Server received a message on " + clientPort + ".");
    catch(IOException ioe)
    {  System.out.println(clientPort + " ERROR reading: " + ioe.getMessage());
    server.remove(clientPort);
    stop();
    etc. Please advice why the readLine() method hangs; does not read data from the input stream received from the CLIENT?

  • Sockets Problem - 2

    Per Dr.Clap's request I have created a new thread....here is the code
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    public class FTPClient {
         public static void main(String[] args) throws IOException {
              if (args.length != 1) {
                   System.out.println("Usage: java FTPClient <hostname>");
                   System.exit(0);
              InetAddress addr = InetAddress.getByName(args[0]);
              // connect to the server
              Socket socket = new Socket(addr, 21);
              try {
                   boolean running = true;
                   BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                   PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                   BufferedReader keyboardInput = new BufferedReader(new InputStreamReader(System.in));
                   System.out.println("Enter a command and hit Enter, type exit to quit the program");
                   while (socket.isConnected() &&  running) {
                        System.out.print("client_shell>");
                        String cmd =  keyboardInput.readLine();
                        if (cmd == null || cmd.length() == 0) {
                             continue;
                        else if (cmd.equalsIgnoreCase("exit") || cmd.equalsIgnoreCase("stopandexit")) {
                             out.println(cmd);
                             running = false;
                        else {
                             out.println(cmd);
                             String result = readResponse(in);
                             System.out.println(result);
                             System.out.println();
              catch (Exception e) {
                   e.printStackTrace();
              finally {
                   System.out.println("Closing connection with " + args[0] + ":21");
                   socket.close();
         private static String readResponse(BufferedReader reader) throws Exception {
              StringBuffer sb = new StringBuffer();
              String line = null;
              while ( (line = reader.readLine()) != null) {
                   sb.append(line);
                   System.out.print(line);
              System.out.println("CLIENT DONE WITH SERVER RESPONSE");
              return sb.toString();
    Server
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class FTPServer {
         public static void main(String[] args) throws IOException {
              final int PORT = 21;
              String validClientAddress = null;
              if (args.length == 1) {
                   validClientAddress = args[0];
              else {
                   System.out.println("Usage: java FTPServer <client_address>");
                   System.exit(0);
              ServerSocket ss = new ServerSocket(PORT);
              boolean serverRunning = true;
              try {
                   System.out.println("Started Server on port " + PORT);
                   BufferedReader in = null;
                   PrintWriter out = null;
                   while (serverRunning) {
                        Socket socket = ss.accept();
                        boolean validConnection = (socket.getInetAddress().getHostAddress().equals(validClientAddress));
                        if (validConnection == false) {
                             System.out.println("Client not allowed to connect: " + socket.getInetAddress().getHostName() + ":" + socket.getPort());
                             socket.close();
                        else {
                             System.out.println("Connected to " + socket.getInetAddress().getHostName() + ":" + socket.getPort());
                             while (socket.isConnected() && serverRunning) {
                                  try {
                                       in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                                       out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                                       StringBuffer cmd = new StringBuffer();
                                       int tmp = -1;
                                       while ( (tmp = in.read()) != -1) {
                                            cmd.append((char) tmp);
                                       if (cmd != null && cmd.length() > 0) {
                                            System.out.println("Executing: " + cmd);
                                            if (cmd.toString().equalsIgnoreCase("exit")) {
                                                 System.out.println("Closed connection to " + socket.getInetAddress().getHostName() + ":" + socket.getPort());
                                                 try {
                                                      socket.close();
                                                      socket = ss.accept();
                                                      System.out.println("Connected to " + socket.getInetAddress().getHostName() + ":" + socket.getPort());
                                                 } catch (Exception e) {}
                                            else if (cmd.toString().equalsIgnoreCase("stopandexit")) {
                                                 serverRunning = false;
                                            else {
                                                 Process p = Runtime.getRuntime().exec(cmd.toString());
                                                 ProcessStreamGobbler psg = new ProcessStreamGobbler(p, false, true);
                                                 BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                                                 StringBuffer sb = new StringBuffer();
                                                 String line = null;
                                                 while ( (line = reader.readLine()) != null) {
                                                      sb.append(line);
                                                      sb.append("\r\n");
                                                 System.out.println("Sending response for command=" + cmd + " (" + sb.toString().getBytes().length + " bytes)");
                                                 out.println(sb);
                                  catch (Exception e) {
                                       serverRunning = false;
                                       e.printStackTrace();
                                  finally {
                                       if (serverRunning == false) {
                                            System.out.println("Closed connection to " + socket.getInetAddress().getHostName() + ":" + socket.getPort());
                                            socket.close();
              catch (Exception e) {
                   e.printStackTrace();
              } finally {
                   System.out.println("Closing server");
                   ss.close();
    }I know it's not very pretty...but the point is if you start the server (in its own console)
    java FTPServer 127.0.0.1
    ..then start the client (in its own console)
    java FTPClient localhost
    ..then try running a command. From the client try, ipconfig . ...you will see nothing gets printed out.
    Any ideas why?
    Thanks.

    Perhaps the while loop in that method neverequates
    to false?yes your right, it hangs up b/c line ends up being
    equal to "" .....but how else would i read from the
    reader? I cant check for just "" b/c an empty line
    is valid...
    any ideas??Maybe the method that returns that string should return null instead of an empty line, when there really isn't any input.

  • Program to check existence of a url hangs!!!

    Here is my code to check whether a url exists ...
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class urlExists
         urlExists()
         public int exists(String urlname) throws IOException
              URL url=null;
              try
                url=new URL(urlname);
              catch(Exception e)
                HttpURLConnection connexion = (HttpURLConnection)(url.openConnection());
                if(connexion.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND)
                        return(0);
                else return(1);
    }I am using this class many a times but it keeps on hanging for some reason or another. Could anyone please explain me the reason?
    Thanks in advance.
    Regards
    kbhatia

    you will have to use a Socket:
    public String getResponse(String url) throws Exception{
            int timeout   = 30000; // 30 second timeout
            String inputLine = null;
            Socket socket    = null;
            BufferedReader reader = null;
            Writer writer    = null;
            StringBuffer buf = new StringBuffer();
            try{
                URL server = new URL(url);
                int port = server.getPort();
                if (port < 0)
                    port = 80;
                socket = new Socket(server.getHost(),port);
                writer = new OutputStreamWriter(socket.getOutputStream(), "US-ASCII");
                writer.write("GET " + server.toExternalForm() + " HTTP/1.0\r\n");
                writer.write("Host: " + server.getHost() + ':' + port + "\n\n");
                writer.flush();
                socket.setSoTimeout(timeout);
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
                String line = reader.readLine();
                if (line != null && line.startsWith("HTTP/")){
                    int space = line.indexOf(' ');
                    String status = line.substring(space + 1,space + 4);
                    if (!status.equals("200")){
                        throw new Exception("HTML Error: + " status);
                    while((line = reader.readLine()) != null)
                        buf.append(line).append("\n");
                else{
                    throw new Exception("Bad protocol");
            catch (InterruptedIOException e) {
                throw new Exception("Read timeout expired");
            finally{
                // close the reader, writer, and socket here
            return buf.toString();      
    }

  • Using sockets...

    I'm trying to write a fairly simple client and server. I want them both to not try to connect until a "Connect" button is pressed in their respective GUIs. The idea is that this is a JToggleButton, which if you press it again, it stops trying to connect, or breaks off the connection if it's already connected. I thought this would be something fairly simple to write, but it seems not, as I'm inundated with errors at every point. I would think this would be a fairly obvious thing to do, but I can't find any examples of anyone else doing anything similar. Can anyone help?
    Also, is it good practice to have a while(in.readLine()) loop? This causes my programs to hang, as it's stuck reading input, and not doing other things. So I put all the server code inside a new Thread()... is this the right way to go about things? What do other people do? Thanks for any help!
    Here's my server code...
           listenBtn.addItemListener(new ItemListener() {
                public void itemStateChanged(ItemEvent event) {
                     if(listenBtn.isSelected()) {
                          new Thread() {
                                    setDaemon(true);
                               @Override
                               public void run() {
                                    logger.info("Listening for a client on port " + portTxt.getText() + "...");
                                    try {
                                         server = new ServerSocket(Integer.parseInt(portTxt.getText()));
                                    catch(IOException exception) {
                                         logger.warning("Could not listen on port " + portTxt.getText() + ".");
                                    try {
                                         client = server.accept();
                                    catch(IOException exception) {
                                         logger.warning("Error connecting to client.");
                                    if(client != null) {
                                           logger.info("Client connected!");
                                    String inputLine, outputLine;
                                    try {
                                         out = new PrintWriter(client.getOutputStream(), true);
                                         in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                                    catch (IOException exception) {
                                         logger.warning("Error initialising streams.");
                                    outputLine = null;
                                    out.println(outputLine);
                                    try {
                                         while((inputLine = in.readLine()) != null) {
                                              text1.setText(inputLine);
                                              outputLine = text2.getText();
                                              out.println(outputLine);
                                    catch(IOException exception) {
                                         logger.warning("Error in input loop.");
                          }.start();
                     else {
                          try {
                               if(out != null) {
                                      out.close();
                               if(in != null) {
                                      in.close();
                               if(client != null) {
                                    client.close();
                               if(server != null) {
                                    server.close();
                          catch (IOException exception) {
                               logger.warning("Error closing streams or sockets.");
                          logger.info("Listening ended.");
           });And my client code...
               connectBtn.addItemListener(new ItemListener() {
                public void itemStateChanged(ItemEvent event) {
                     if(connectBtn.isSelected()) {
                       System.out.println("Connecting...");
                       try {
                            socket = new Socket(hostTxt.getText(), Integer.parseInt(portTxt.getText()));
                            out = new PrintWriter(socket.getOutputStream(), true);
                            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                       catch (UnknownHostException exception) {
                            System.err.println("Host cannot be identified.");
                            connectBtn.setSelected(false);
                       catch (IOException exception) {
                            System.err.println("Couldn't get I/O for the connection.");
                            connectBtn.setSelected(false);
                   if(socket != null) {
                        System.out.println("Connected!");
                       String send, recieved;
                       try {
                            while((recieved = in.readLine()) != null) {
                                 intervalTxt.setText(recieved);
                                 send = spikesTxt.getText();
                                 if(send != null) {
                                      out.println(send);
                       catch(IOException exception) {
                            System.err.println("Error reading input stream.");
                            connectBtn.setSelected(false);
                     else {
                          try {
                               if(out != null)     {
                                        out.close();
                               if(in != null)     {
                                        in.close();
                               if(socket != null)     {
                                    socket.close();
                        catch(IOException exception) {
                             System.err.println("Error closing streams or socket.");
                        System.out.println("Connecting ended.");
              });

    * In the server, if I click Listen (to search for a client), then I click it again to stop listening (without a client connecting), I get a NullPointerException on this line:
    out = new PrintWriter(client.getOutputStream(), true);Obviously 'client' is null.
    * Similarly, in the client, when I click Connect when the server is not running, I get a NullPointerException on the line:
    while((recieved = in.readLine()) != null) {Obviously 'in' is null.
    These are elementary errors. You don't need forums to find them.
    * In the server, I want to be able to detect when the client has disconnected or connected. I've got some code that detects when a client has connected, but I'm not sure I'm going about it in the best way.There's only one way. ServerSocket.accept() returns.
    And I need some way to detect when a client has disconnected.read() will return -1, readLine() will return null, readXXX() will throw EOFException for any other XXX, or any write method will throw an IOException: connection reset.
    * The same thing in the client; I want to know when the server has stopped listeningSee above.
    or when the client successfully connects to the server.new Socket(...) returns.
    * In the server, I'm doing some OpenGL stuff. As soon as the client connects, the OpenGL stuff stops moving, and becomes totally unresponsive.That will be either because your client session isn't running in a separate thread or it is locked in a hard loop.

Maybe you are looking for

  • Why is my text blurry?

    I've  used fireworks to create my banner, which includes a background color in a rectangle, and my company name in a text box @ a 75 text size.  It ends up looking blurry.  Is there a way to create a large - crisp looking text? Should I go about this

  • After upgrade to latest firmware canon network printer won't print

    after upgrade to latest firmware canon network printer won't print. It's a canon MP540 on a wireless network. It will print a test page but won't print from any application, just sits there with the message 'copying print data'! Running Mac OS X Lion

  • Finalizer memory leak addemndum

    In my last post, I forgot to mention that the Finalizer referent for all 200000 objects was java.net.Socket*

  • What are the ideal system requirements for Adobe Captivate?*

    What are the ideal system requirements for Adobe Captivate?* In order to ensure it runs at a good speed.

  • Disk IO monopolized by one app

    Hi, I have a desktop and a notebook, by hardware upgrade issues i'm using only my notebook, On my desktop, i have four hard driver 7200RPM SATA II so i've only notices this problem when using VMWare and i  was thinking that was a VMWare problem, but,