Java BufferedReader frozen [duplicate] - java

I wanna write the code to let Client send a string to Server, Server print the string and reply a string, then Client print the string Server reply.
My Server
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = null;
Socket s = null;
try {
ss = new ServerSocket(34000);
s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream());
while (true) {
String string = in.readLine();
if (string != null) {
System.out.println("br: " + string);
if (string.equals("end")) {
out.write("to end");
out.flush();
out.close();
System.out.println("end");
// break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
s.close();
ss.close();
}
}
}
My Client:
public class Client {
public static void main(String[] args) {
Socket socket =null;
try {
socket = new Socket("localhost", 34000);
BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
String string = "";
string = "end";
out.write(string);
out.flush();
while(true){
String string2 = in.readLine();
if(string2.equals("to end")){
System.out.println("yes sir");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
System.out.println("closed client");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
are there some somethings wrong? if i remove the code "while(true) ..." in client class, it's OK.

you should add "\r\n" at the end of the String which write into stream.
example:
client :
string = "end";
out.write(string + "\r\n");
out.flush();
server :
out.write("to end" + "\r\n");
out.flush();
out.close();
System.out.println("end");
// break;

I don't see the server response.
You do a
System.out.println("br: " + string);
but not a
out.write(string);
out.flush();

Appand "\n" to end of the response from server.
outToClient.writeBytes(sb.toString() + "\n");

You are reading lines but you aren't writing lines. Add a newline, or call BufferedReader.newLine().

Related

Java, Sockets, BufferedReader and StringBuilder

Yestarday I wrote a post about Java and Sockets, and today I'm still here because I'm having an issue with BufferedReaders.
I searched some questions here in StackOverflow and I understand the problem, but I can't fix it
My "application" has got two parts: a server and a client, and the scope of the application is to execute MS-DOS commands on the machine where the server is running (the commands are sent by the client).
Now the code (I will post the total code because it's easier to understand, I will put a comment in non-working part of the code) Server:
import java.net.*;
import java.io.*;
public class TCPCmdServer {
public int port;
public ServerSocket server;
public final String version = "Beta 1.0";
TCPCmdServer(int port) {
this.port = port;
if (!createServer())
System.out.println("Cannot start the server");
else {
System.out.println("**********************************************");
System.out.println("Command executer, server version: " + version);
System.out.println("Server running on port " + port);
System.out.println("Code by luc99a alias L99");
System.out.println("**********************************************");
}
}
public boolean createServer() {
try {
server = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public static void main(String[] args) {
TCPCmdServer tcp = new TCPCmdServer(5000);
while (true) {
Socket socket = null;
BufferedReader in = null;
BufferedWriter out = null;
try {
socket = tcp.server.accept();
System.out.println("A client has connected");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("Welcome on the server... type the commands you like, type END to close the connection\n");
out.flush();
} catch (IOException exc) {
exc.printStackTrace();
}
if (socket != null && in != null && out != null) {
try {
String cmd = null;
while (!(cmd = in.readLine()).equals("END")) {
System.out.println("Recieved: " + cmd);
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader pRead = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
StringBuilder builder = new StringBuilder();
while ((line = pRead.readLine()) != null) {
builder = builder.append(line + "\n");
}
out.write(builder.toString() + "\n");
//here is sent "EnD"
out.write("EnD \n");
out.flush();
System.out.println(builder.toString());
pRead.close();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
System.out.println("Closing connection...");
try {
socket.close();
in.close();
out.close();
} catch (IOException excp) {
excp.printStackTrace();
}
}
}
}
}
}
And now the code for the client part
import java.net.*;
import java.io.*;
public class TCPCmdClient {
public Socket socket;
public int port;
public String ip;
public final String version = "Beta 1.0";
TCPCmdClient(String ip, int port) {
this.ip = ip;
this.port = port;
if (!createSocket())
System.out.println("Cannot connect to the server. IP: " + ip + " PORT: " + port);
else {
System.out.println("**********************************************");
System.out.println("Command executer, client version: " + version);
System.out.println("Connected to " + ip + ":" + port);
System.out.println("Code by luc99a alias L99");
System.out.println("**********************************************");
}
}
public boolean createSocket() {
try {
socket = new Socket(ip, port);
} catch (IOException e) {
return false;
}
return true;
}
public static void main(String[] args) {
TCPCmdClient client = new TCPCmdClient("127.0.0.1", 5000);
try {
BufferedReader sysRead = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(client.socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.socket.getOutputStream()));
String response = in.readLine();
System.out.println("Server: " + response);
boolean flag = true;
while (flag) {
System.out.println("Type a command... type END to close the connection");
String cmd = sysRead.readLine();
out.write(cmd + "\n");
out.flush();
if (cmd.equals("END")) {
client.socket.close();
sysRead.close();
in.close();
out.close();
flag = false;
} else {
//The loop doesn't finish because the reader
//listens for a new line
//so I used the string "EnD", sent by the server to
//stop the loop, anyway it doesn't seem to work
//I put a comment in the server where "EnD" is sent
String output;
while (((output = in.readLine()) != null)) {
if (output.equals("EnD")) {
break;
} else {
System.out.println(output);
}
}
System.out.println(" *************************************** ");
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
The problem is that the BufferedReader waits for a new line forever in the while loop (I wrote a comment in the code). I tryed to stop it using a "special string", but it doesn't seem to work.
I can't change the while in
String output;
while (((output = in.readLine()) != null) && output.length > 0)
{
//code here...
}
because in the output of the MS-DOS command (think on "ipconfig") are also present empty lines.
How could I correct it?
Thank you for your help!
your client Sends "EnD " (with a whitespace at the end) and you are comparing to "EnD" without a whitespace. So the two strings are not equal. try to send it without the white space:
out.write("EnD\n");
Space is missing. In TCPCmdClient.java change
if (output.equals("EnD")) {
to
if (output.equals("EnD ")) {

BufferedReader from server does not work

In this code I can correctly receive a request using BufferedReader inClient, created on the client socket.
Then I send the request to the server and I see the server gets it.
But then, when I try to read the reply from the server (using BufferedReader inServer on the socket of the server), it always ends in IOException: Impossible read from server.
I am referring to the block ################
Do you know any possible reasons?
import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ProxyMain {
public static void main(String argv[]) {
int proxyPort = 55554;
String proxyAddr = "127.0.0.1";
ServerSocket proxySocket = null;
try {
proxySocket = new ServerSocket(proxyPort, 50, InetAddress.getByName("127.0.0.1"));
}
catch (Exception e) {
System.err.println("Impossible to create socket server!");
System.out.flush();
System.exit(1);
}
System.out.printf("Proxy active on port: %d and on address %s\n", proxyPort, proxySocket.getInetAddress());
System.out.println();
while (true) {
Socket client = null;
Socket sockServ = null;
BufferedReader inClient = null;
PrintWriter outClient = null;
BufferedReader inServer = null;
PrintWriter outServer = null;
String request = new String();
String tmp = new String();
String reply = new String();
String tmpReply = new String();
try {
client = proxySocket.accept();
System.out.println("Connected to: ");
System.out.println(client.getInetAddress().toString());
System.out.printf("On port %d\n", client.getPort());
System.out.println();
inClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
outClient = new PrintWriter(client.getOutputStream(), true);
}
/*catch (IOException e) {
System.err.println("Couldn't get I/O for connection accepted");
System.exit(1);
}*/
catch (Exception e) {
System.out.println("Error occurred!");
System.exit(1);
}
System.out.println("Received request:");
try{
for (int i = 0; i<2; i++) {
tmp = inClient.readLine();
request = request + tmp;
}
inClient.close();
}
catch (IOException ioe) {
System.err.println("Impossible to read mhttp request!");
System.exit(1);
}
System.out.println(request);
System.out.println();
try {
sockServ = new Socket("127.0.0.1", 55555);
outServer = new PrintWriter(sockServ.getOutputStream(), true);
inServer = new BufferedReader(new InputStreamReader(sockServ.getInputStream()));
}
catch (UnknownHostException e) {
System.err.println("Don't know about host: 127.0.0.1:55555");
System.exit(1);
}
catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: 127.0.0.1:55555");
System.exit(1);
}
outServer.println(request);
outServer.close();
try {
#################################################
while ((tmpReply = inServer.readLine()) != null) {
System.out.println(tmpReply);
reply = reply + tmpReply;
}
inServer.close();
sockServ.close();
}
catch (IOException ioe) {
System.err.println("Impossible to read from server!");
System.exit(1);
}
outClient.println(reply);
outClient.close();
try {
client.close();
}
catch (IOException ioe) {
System.err.printf("Impossible to close connection with %s:%d\n", client.getInetAddress().toString(), client.getPort());
}
}
}
}
UPDATE:
It seems that if I do:
boolean res = inServer.ready();
it always return false.
So Server is not ready to send the reply but this is strange...with my Project in C e Python it worked immediately. Why should java be different?
When you close outServer, you close the underlying socket. if you just want to close the output and keep the input open, you need to use Socket.shutdownOutput(). note, you have the same problem when you close inClient.
This works, maybe you can get some ideas from it...
ChatServer - broadcasts to all connected clients
In one command prompt: java ChartServer
In another: java ChatClient localhost (or the ip address of where the server is running)
And another: java ChatClient localhost (or the ip address of where the server is running)
Start chatting in the client windows.
Server like this...
// xagyg wrote this, but you can copy it
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
public static List list = new ArrayList();
public static void main(String[] args) throws Exception {
ServerSocket svr = new ServerSocket(4444);
System.out.println("Chat Server started!");
while (true) {
try {
Socket s = svr.accept();
synchronized(list) {
list.add(s);
}
new Handler(s, list).start();
}
catch (IOException e) {
// print out the error, but continue!
System.err.println(e);
}
}
}
}
class Handler extends Thread {
private Socket s;
private String ipaddress;
private List list;
Handler (Socket s, List list) throws Exception {
this.s = s;
ipaddress = s.getInetAddress().toString();
this.list = list;
}
public void run () {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
String message;
//MyDialog x = (MyDialog)map.get(ipaddress.substring(1));
while ((message = reader.readLine()) != null) {
if (message.equals("quit")) {
synchronized(list) {
list.remove(s);
}
break;
}
synchronized(list) {
for (Object object: list) {
Socket socket = (Socket)object;
if (socket==s) continue;
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println(ipaddress + ": " + message);
writer.flush();
}
}
}
try { reader.close(); } catch (Exception e) {}
}
catch (Exception e) {
System.err.println(e);
}
}
}
Client like this ...
// xagyg wrote this, but you can copy it
import java.util.*;
import java.io.*;
import java.net.*;
public class ChatClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket(args[0], 4444);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String message;
new SocketReader(in).start();
while ((message = reader.readLine())!=null) {
out.println(message);
out.flush();
if (message.equals("quit")) break;
}
in.close();
out.close();
}
}
class SocketReader extends Thread {
BufferedReader in;
public SocketReader(BufferedReader in) {
this.in = in;
}
public void run() {
String message;
try {
while ((message = in.readLine())!=null) {
System.out.println(message);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}

BufferedWriter.write() does not seem to work

I have two Java applications, where an Android client connects to a server on a computer and sends a message using BufferedWriter over websockets.
The client:
try {
toast("Sending...");
Socket sock = new Socket(ip, PORT);
OutputStream os = sock.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.flush();
bw.write("Hello Server!");
toast("Connected!");
} catch (UnknownHostException e) {
toast(e.getMessage());
} catch (IOException e) {
toast(e.getMessage());
}
The server:
public static void main(String[] args) {
ServerSocket server;
ConnectionThread ct;
Socket s;
ExecutorService es = Executors.newSingleThreadExecutor();
try {
System.out.println("Starting server...");
server = new ServerSocket(1337);
s = server.accept();
ct = new ConnectionThread(s);
es.execute(ct);
} catch (IOException ex) {
ex.printStackTrace();
}
}
The ConnectionThread class:
public class ConnectionThread implements Runnable {
private Socket sock;
private InputStream is;
private BufferedReader br;
private boolean online;
public ConnectionThread(Socket s) {
System.out.println("Creating connection thread.");
this.sock = s;
online = true;
}
#Override
public void run() {
String input = "";
try {
System.out.println("Starting to read...");
is = sock.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while (online) {
input = br.readLine();
if(input != null){
System.out.print("Received message: ");
System.out.println(input);
}
}
br.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
When I run the server, and then the client, the client will show the "Connected!" toast, and the server's output will be:
Starting server...
Creating connection thread.
Starting to read...
So, it seems like the connection is actually being made, but the message does not arrive. Does anybody know why this could be happening?
Your server is expecting a complete line terminated by a newline. Try:
bw.write("Hello Server!");
bw.newLine();
Do it like this...
String s = new String();
while ((br.readLine())!=null) {
s = s+br.readLine();
System.out.print("Received message: ");
System.out.println(input);
}
}
And
bw.println("Hello Server");
I notice that you don't send an endline on your client, so the BufferedReader.readline() will never return, because it cannot match the \n-character. Try it again with
bw.write("Hello Server!\n");
on the client side.

Console based login application using java sockets

I am making a console based java application - which will check the username and password of client. What I want is the data entered by client must enter to server in a line by line format i.e pressing enter must send username data and password for next enter press. But what the problem is - until I quit at the client side the data is not sent to the server. Meaning , when client hits 'Bye.' then the client is closed and server receives the data then. Help me in this regard as this is the first step - later I have to check database with this username and password on server. My codes are as follows :
Server :
import java.net.*;
import java.io.*;
public class EchoServer2 extends Thread
{
protected Socket clientSocket;
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(2010);
System.out.println ("Connection Socket Created");
try {
while (true)
{
System.out.println ("Waiting for Connection");
new EchoServer2 (serverSocket.accept());
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port.");
System.exit(1);
}
finally
{
try {
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port.");
System.exit(1);
}
}
}
private EchoServer2 (Socket clientSoc)
{
clientSocket = clientSoc;
start();
}
public void run()
{
System.out.println ("New Communication Thread Started");
try {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
PrintWriter out1 = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
BufferedReader in1 = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine,u,p;
while ((u = in.readLine()) != null && (p = in.readLine()) != null)
{
System.out.println ("U: " + u);
out1.println(u);
System.out.println ("P: " + p);
out1.println(p);
if (u.equals("Bye."))
break;
}
out1.close();
out.close();
//in1.close();
in.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("Problem with Communication Server");
System.exit(1);
}
}
}
Client :
import java.io.*;
import java.net.*;
import java.lang.*;
import java.io.Console;
public class EchoClient2 {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port .");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader in1 = null;
try {
echoSocket = new Socket(serverHostname, 2010);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
BufferedReader std = new BufferedReader(
new InputStreamReader(System.in));
String upwd,uname,text;
Console console = System.console();
String username = console.readLine("Username:");
char[] pwd = console.readPassword("Password:");
upwd=new String(pwd);
while (username!=null && upwd!=null && (uname = stdIn.readLine()) != null)
{
out.println("Username:"+username);
out.println("Password:"+upwd);
// end loop
if (uname.equals("Bye."))
break;
}
out.close();
stdIn.close();
echoSocket.close();
}
}
On the client side, do out.flush() after writing the password to the stream.

BufferedWriter does not flush

I have the following problem....
try
{
clientInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
clientOutput = new BufferedWriter(new PrintWriter(clientSocket.getOutputStream()));
while(true)
{
String clientRequest = "";
String tempStr = clientInput.readLine();
while(tempStr != null && !tempStr.equals("null"))
{
System.out.println(tempStr);
clientRequest += tempStr + " ";
tempStr = clientInput.readLine();
}
//Parse Request
ArrayList<String> tokenArray = parseRequest(clientRequest);
Calendar c = Calendar.getInstance();
switch(tokenArray.get(0))
{
case "GET":
{
clientOutput.write("HTTP/1.1 200 OK\r\n");
clientOutput.write("Date: " + c.getDisplayName(0, Calendar.LONG, Locale.UK).toString() + "\r\n");
clientOutput.write("Server: Java HTTP Server v1.0\r\n");
clientOutput.flush();
break;
//Write File
}
default:
{
clientOutput.write("500\r\n");
clientOutput.flush();
}
}
}
}
Every thing works completely fine up-and-till the clientOutput.write("HTTP....... line,
the client just keeps waiting and waiting... i've attempted to flush after every sucsessive write and yet nothing..... BUT This is the weird part - if i write to and flush before the code enters the while-loop the the writes in the case "GET": works perfectly...... ie
The code does execute all the way to the
clientOutput.flush();
break;
//Write File
.
try
{
clientInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
clientOutput = new BufferedWriter(new PrintWriter(clientSocket.getOutputStream()));
clientOutput.write("HTTP/1.1 200 OK\r\n");
clientOutput.flush();
while(true)
{
String clientRequest = "";
String tempStr = clientInput.readLine();
while(tempStr != null && !tempStr.equals("null"))
{
System.out.println(tempStr);
clientRequest += tempStr + " ";
tempStr = clientInput.readLine();
}
//Parse Request
ArrayList<String> tokenArray = parseRequest(clientRequest);
Calendar c = Calendar.getInstance();
switch(tokenArray.get(0))
{
case "GET":
{
clientOutput.write("HTTP/1.1 200 OK\r\n");
clientOutput.write("Date: " + c.getDisplayName(0, Calendar.LONG, Locale.UK).toString() + "\r\n");
clientOutput.write("Server: Java HTTP Server v1.0\r\n");
clientOutput.flush();
break;
//Write File
}
Here is the code for the client
Socket s = new Socket("localhost", 1337);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter toServer = new BufferedWriter(new PrintWriter(s.getOutputStream()));
toServer.write("GET index.html HTTP/1.1\r\n");
toServer.write("HOST: 127.0.0.1\r\n");
toServer.write("Connection: close\r\n");
toServer.write("\r\n");
toServer.write("null\r\n");
toServer.flush();
while(true)
{
String ss = fromServer.readLine();
if(ss != null && !ss.equals("null"))
System.out.println(ss);
}
Server Class: Strydom_A_201103578_P03
public class Strydom_A_201103578_P03
{
Thread[] threadArray = new Thread[5];
int ClientCount = 0;
public Strydom_A_201103578_P03() throws ClientSizeExceededException
{
ServerSocket httpServer = null;
try
{
httpServer = new ServerSocket(1337);
}
catch (IOException ex)
{
Logger.getLogger(Strydom_A_201103578_P03.class.getName()).log(Level.SEVERE, null, ex);
}
while(true)
{
try
{
//Wait for connection
Socket clientSocket = httpServer.accept();
if(ClientCount < 5)
{
threadArray[ClientCount] = new Thread(new clientHandler(clientSocket));
threadArray[ClientCount].start();
ClientCount++;
}
else
{
throw new ClientSizeExceededException();
}
}
catch(IOException ex)
{
}
finally
{
}
}
}
class clientHandler implements Runnable
{
Socket clientSocket;
public clientHandler(Socket clientSocket)
{
this.clientSocket = clientSocket;
}
#Override
public void run()
{
BufferedReader clientInput = null;
BufferedWriter clientOutput = null;
try
{
clientInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
clientOutput = new BufferedWriter(new PrintWriter(clientSocket.getOutputStream()));
clientOutput.write(" ");
clientOutput.flush();
while(true)
{
String clientRequest = "";
String tempStr = clientInput.readLine();
while(tempStr != null && !tempStr.equals("null"))
{
System.out.println(tempStr);
clientRequest += tempStr + " ";
tempStr = clientInput.readLine();
}
//Parse Request
ArrayList<String> tokenArray = parseRequest(clientRequest);
Calendar c = Calendar.getInstance();
switch(tokenArray.get(0))
{
case "GET":
{
clientOutput.write("HTTP/1.1 200 OK\r\n");
clientOutput.write("Date: " + c.getDisplayName(0, Calendar.LONG, Locale.UK).toString() + "\r\n");
clientOutput.write("Server: Java HTTP Server v1.0\r\n");
clientOutput.flush();
break;
//Write File
}
default:
{
clientOutput.write("500\r\n");
clientOutput.flush();
}
}
}
}
catch (IOException ex)
{
Logger.getLogger(Strydom_A_201103578_P03.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
try
{
clientInput.close();
clientOutput.close();
}
catch (IOException ex)
{
Logger.getLogger(Strydom_A_201103578_P03.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private ArrayList<String> parseRequest(String tempStr)
{
StringTokenizer httpTokens = new StringTokenizer(tempStr, " ");
ArrayList<String> tokens = new ArrayList<>();
while(httpTokens.hasMoreTokens())
tokens.add(httpTokens.nextToken());
return tokens;
}
}
public static void main(String[] args) throws ClientSizeExceededException
{
new Strydom_A_201103578_P03();
}
}
public class TestClient
{
public TestClient()
{
try
{
Socket s = new Socket("localhost", 1337);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter toServer = new BufferedWriter(new PrintWriter(s.getOutputStream()));
toServer.write("GET index.html HTTP/1.1\r\n");
toServer.write("HOST: 127.0.0.1\r\n");
toServer.write("Connection: close\r\n");
toServer.write("\r\n");
toServer.write("null\r\n");
toServer.flush();
while(true)
{
String ss = fromServer.readLine();
if(ss != null && !ss.equals("null"))
System.out.println(ss);
}
}
catch (UnknownHostException ex)
{
Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args)
{
new TestClient();
}
}
Client Class: TestClient
Create a project( or 2) and run the files
The problem here is the PrintWriter. It swallows exceptions. Change it to an OutputStreamWriter. Then you will see any exception that is being swallowed. In general you should avoid PrintWriters and PrintOutputStreams over a network. They swallow exceptions that you need to know about.
You need to change your inner while loop to look for the end of the client's request:
while(tempStr != null && !tempStr.equals("null"))
to:
while(tempStr != null && !tempStr.equals("null") && !tempStr.equals(""))
The client won't disconnect (causing a null) after it sends a request. It will give you a blank line to indicate the end of its request.
Reason why returning the response header right away is working? Maybe the client just reads the 200 and (eventually) disconnects? So when you are reading the client's request, it ends and you get a null eventually.
EDIT:
So running your code, it works fine for me. Both the client and server are sending and receiving both requests and responses. However, the server never disconnects (the client includes a Connection: close header) and the client continues to block on readLine(). Unsurprisinly, when I include the write() and flush() immediately after setting up the connection on the server-side nothing changes except I see HTTP/1.1 200 OK twice on the client's end. Maybe all you need to do is close the clientSocket in a finally{} block at the end of your try/catch{}?
So for the futhering of my now ended suffering - here is what i finally did....
I changed both the server and the clients readers from BufferedReader/Writer to DataInputstream/OutputStream.... And it works perfectly now - ! Thanks to everyone
Aiden
Just do this and it will work..........
Add true as the 2nd parameter in the PrintWriter
clientOutput = new BufferedWriter(new PrintWriter(clientSocket.getOutputStream(), true));

Categories