6

Can anyone help me debug this program?

The following is server code :

package networking;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

class TcpServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(5555);
        while (true) {
            Socket client = serverSocket.accept();
            Scanner reader = new Scanner(client.getInputStream());
            PrintWriter writer = new PrintWriter(client.getOutputStream());
            String inputString = reader.nextLine();
            System.out.println("Received from client : " + inputString);
            writer.write(inputString.toUpperCase());
            client.close();
        }
    }
}

And this is the client code :

package networking;

import java.io.PrintWriter;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

class TcpClient {
    public static void main(String[] args) throws IOException {
        Socket client = new Socket("localhost", 5555);
        PrintWriter writer = new PrintWriter(client.getOutputStream());
        Scanner reader=new Scanner(client.getInputStream());
        writer.println("oPen SOurCe RUleS !");
        System.out.println("Received from server : "+reader.nextLine());
        client.close();
    }
}

The problem is that when I run this program both client & server go into indefinite waiting state.Could anyone tell me what's wrong with this code?

Thanks in advance!

4
  • 1
    Is the the correct code? . . . The imports of TcpClient seam to be messed up: not imported PrintWriter and not used the DataOutputStream. . . . Anyway I suggest not to use the PrintWriter since it does NOT throw Exceptions, you have to check for Errors calling checkError. IMHO only good for logging. Commented Dec 12, 2009 at 11:51
  • @Carlos : What should have I used in place of PrintWriter? Commented Dec 12, 2009 at 12:43
  • 1
    I thinked about OutputStreamWriter... or just don't forget to use checkError on the PrintWriter Commented Dec 17, 2009 at 19:54
  • @Carlos : Thanks for the suggestion! I'll sure keep that in mind! :-) Commented Dec 17, 2009 at 19:57

1 Answer 1

7

Have you tried Flushing the PrintWriter?

You close the stream but you never notify the writer that you're about to do so.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.