Hi,
This problem is occurring because of the problem in your code
you have been reading from the socket using BR.readLine in the while loop and then you are checking again by reading one more line in the if condition which means at this point it is reading the second line which might not be exit. it is giving this error because you are terminating the while loop using break without closing the socket connection and so the error..
your while loop should be something like this.
String line = null;
while( (line = BR.readLine()) != null)
{
if (line.equalsIgnoreCase("exit"))
break;
else
pw.write(line);
pw.flush();
}
and you should wait for a few seconds before closing the connection so that termination is proper
the server code should look something like this:-
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
class Server extends Thread
{
public void run()
{
try
{
Thread.sleep(2000);
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
public static void main(String str[]) throws Exception
{
BufferedReader BR;
ServerSocket s_soc;
Socket soc;
s_soc = null;
s_soc = new ServerSocket(90);
soc = s_soc.accept();
BR = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter( soc.getOutputStream(), true);
String line = null;
while( (line = BR.readLine()) != null)
{
if (line.equalsIgnoreCase("exit"))
{
(new Server()).start();
soc.close();
break;
}
else
pw.write(line);
pw.flush();
}
s_soc.close();
}
}
Client Program:-
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
class Client
{
public static void main(String str[]) throws Exception
{
Socket sock = new Socket(InetAddress.getLocalHost(), 90);
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
String getOutput;
while( (getOutput = br.readLine()) != null )
{
System.out.println(getOutput);
out.write(getOutput);
}
out.close();
br.close();
sock.close();
}
}
|