views:

209

answers:

1

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!

+7  A: 

Have you tried Flushing the PrintWriter?

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

Frank Krueger
Thank you! Problem solved!
missingfaktor