Reputation: 2897
I am coding for a single server and multiple client in JAVA . This is my code for server And This is my code for client .
More specifically , I have the following code in my server .
String Name;
try {
os.println("Enter Your Name:");
Name=is.readLine();
os.println("Hello "+ Name +" Welcome To Our Exam System.Please type Exam to take an Exam or type QUIT to Exit");
line=is.readLine();
while(line.compareTo("QUIT")!=0){
os.println(line);
os.flush();
System.out.println("Response to Client : "+line);
line=is.readLine();
}
} catch (IOException e) {
line=this.getName(); //reused String line for getting thread name
System.out.println("IO Error/ Client "+line+" terminated abruptly");
}
catch(NullPointerException e){
line=this.getName(); //reused String line for getting thread name
System.out.println("Client "+line+" Closed");
}
ANd the following code in client.java
try {
s1=new Socket(address, 4445); // You can use static final constant PORT_NUM
br= new BufferedReader(new InputStreamReader(System.in));
is=new BufferedReader(new InputStreamReader(s1.getInputStream()));
os= new PrintWriter(s1.getOutputStream());
}
catch (IOException e){
e.printStackTrace();
System.err.print("IO Exception");
}
System.out.println("Client Address : "+address);
System.out.println("Enter Data to echo Server ( Enter QUIT to end):");
String response=null;
try{
response=is.readLine();
System.out.println(response);
line=br.readLine();
os.println(line);
response=is.readLine();
line=br.readLine();
while(line.compareTo("QUIT")!=0)
{
os.println(line);
os.flush();
response=is.readLine();
System.out.println("Server Response : "+response);
line=br.readLine();
}
}
catch(IOException e){
e.printStackTrace();
System.out.println("Socket read Error");
}
From this code I am expecting the following task :
Then server will do the following line :
os.println("Hello "+ Name +" Welcome To Our Exam System.Please type Exam to take an Exam or
type QUIT to Exit");
But after establishment of connection , no message like " Enter your name " is sent from server to client
Why ?
Upvotes: 1
Views: 117
Reputation: 191
Add the following line after Server, LINE 68:
the client will show the expected "Enter your name".
Both server and client are waiting for input, thus sitting in a deadlock. You must call os.flush() to actually sed your data to the server.
Your server code writes to output but doesn't send it:
Then the client hangs because the server didnt send it via os.flush() at:
while your server is also waiting for the clients answer at
Source for the os.flush command was this sample code: https://stackoverflow.com/a/5680427/3738721
Upvotes: 1