Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Client stuck on readLine

760978Nov 18 2008 — edited Nov 22 2008
Hi,

I'm trying to do a communication between a server and a client (not using threads for now). The problem that I have is when I send multiple messages from the server to the client. To read the messages on the client I use a loop with a readLine call on the BufferedReader. The problem is when the server doesn't send anymore messages the client is stuck on the last call to readLine. If I close the connection in the server it works, but I have more work to do on the in and out streams before closing the connection.


The client
import java.io.*;
import java.net.*;

public class TimeClient {
	private static final int serverPort = 6000;
	private static final String serverAddress = "Najat";
	
	public static void main(String[] agrs) throws Exception {		
					

		Socket clientSocket = new Socket(serverAddress, serverPort);					
		
		BufferedReader in = ReadWrite.getSocketReader(clientSocket);
		
		String response;
		
		while ((response = in.readLine()) != null) {
			System.out.println(response);
		}
	}
}
The server
import java.io.*;
import java.net.*;
import java.util.*;


public class TimeServer {
	private static final int port = 6000;
	
	public static void main(String[] args) throws Exception {
		ServerSocket serverSocket;
		
		serverSocket = new ServerSocket(port);
		System.out.println("Time server OK");
		
		while (true) {						
						
			Socket clientSocket = serverSocket.accept();
			
			System.out.print("Client connected, IP address: ");
			System.out.println(clientSocket.getRemoteSocketAddress());
			
			BufferedReader in = ReadWrite.getSocketReader(clientSocket);						
			PrintWriter out = ReadWrite.getSocketWriter(clientSocket);
							
			out.println("Welcome to the time server: ");	
			out.println("Type h for time, q to quit: ");
		
		}
	}
}
a helper class
import java.io.*;
import java.net.*;

public class ReadWrite {
	public static BufferedReader getSocketReader(Socket s) throws IOException {
		return new BufferedReader(new InputStreamReader(s.getInputStream()));
	}
		
	public static PrintWriter getSocketWriter(Socket s) throws IOException {
		return new PrintWriter(s.getOutputStream(), true);
	}
}
Edited by: Exhortae on Nov 18, 2008 7:56 PM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 20 2008
Added on Nov 18 2008
9 comments
743 views