Komal Joshi Komal Joshi - 2 months ago 19
Java Question

Server-Client JAVA socket programming error

I am new to socket programming and want to create a client that sends a number and server returns the number multiple of number sent by client. I run the server first and then the client. I am entering the value but not getting any response from server. Following is my client and server code.

Server code

try
{
ServerSocket ss=new ServerSocket(4000);
while(true)
{
Socket sock=ss.accept();
InputStreamReader isr=new InputStreamReader(sock.getInputStream());
BufferedReader br=new BufferedReader(isr);
String num=br.readLine();
try
{
int n=Integer.parseInt(num);
n=n*2;
String ret=String.valueOf(n);
PrintWriter writer=new PrintWriter(sock.getOutputStream());
writer.println(ret);
writer.close();
}
catch(IOException ex)
{
System.out.println("Enter a number!");
}
}
}
catch(Exception ex)
{
System.out.println("Error");
}


Client code

try
{
Socket s=new Socket("127.0.0.1",4000);
String st;
PrintWriter pw=new PrintWriter(s.getOutputStream());
InputStreamReader isr=new InputStreamReader(s.getInputStream());
BufferedReader br=new BufferedReader(isr);
InputStreamReader is=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(is);
st=in.readLine();
pw.println(st);
st=br.readLine();
System.out.println("the server says: "+ st);
}
catch(IOException ex)
{
ex.printStackTrace();
}


Please suggest what steps to follow as I am not getting any output from server.

Answer

The problem lies with this part of the client code, which sends st via pw and then claims st is the server's output.

pw.println(st);
System.out.println("the server says: "+ st);

You should be able to fix the problem actually getting a value from the server via br. You also need to flush pw:

pw.println(st);
pw.flush();
st = br.readLine();
System.out.println("the server says: "+ st);

Alternatively, you can make pw auto-flushing like so:

PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
// ...
pw.println(st);
st = br.readLine();
System.out.println("the server says: "+ st);
Comments