Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem in TCP Program (Java)

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!

like image 985
missingfaktor Avatar asked Nov 22 '09 07:11

missingfaktor


1 Answers

Have you tried Flushing the PrintWriter?

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

like image 115
Frank Krueger Avatar answered Sep 20 '22 23:09

Frank Krueger