count the number of bytes that java web client sends and receives - java

I have Simple web client written on Java and I have to count the number of bytes that it sends and recieves. Then I have to compare results with netstat -s command. Also, how can i measure average size of the packets I sent and receive.
Here is WebClient.java:
package javaapplication1;
/**
*
* #author
*/
import java.net.*;
import java.io.*;
import java.util.*;
public class WebClient {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter host name (e.g., www.ouhk.edu.hk): ");
String host = scanner.nextLine();
System.out.print("Enter page (e.g., /index.html): ");
String page = scanner.nextLine();
final String CRLF = "\r\n"; // newline
final int PORT = 80; // default port for HTTP
try {
Socket socket = new Socket(host, PORT);
OutputStream os = socket.getOutputStream();
InputStream is = socket.getInputStream();
PrintWriter writer = new PrintWriter(os);
writer.print("GET " + page + " HTTP/1.1" + CRLF);
writer.print("Host: " + host + CRLF);
writer.print(CRLF);
writer.flush(); // flush any buffer
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null){
System.out.println(line);
}
System.out.println("Recieved bytes:");
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

You could create your own implementations of FilterInputStream and FilterOutputStream that will count all data passed through. Then just use them as filters, for example:
OutputStream os = new CountingOutpurStream(socket.getOutputStream());
InputStream is = new CountingInputStream(socket.getInputStream());

Related

No response form Server Socket Java

Please help, connection to server has been made but the server willl not respond to any requests. Just trying to get the time and date working by sending the server "1". P.s i know i should not have all of the cases of 1-7 but i just want to get the date ad time working before worrying about any others
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;
/**
*
* #author samdo
*/
public class SocketProgrammingSamD {
/**
* #param args the command line arguments
*/
private static Scanner in;
public static void main(String[] args) throws IOException {
System.out.println("Samuel Donini");
System.out.println(" ");
System.out.println("Project 1");
System.out.println(" ");
System.out.println(" ");
//new Driver().execute(args);//Creates an instance of the Driver class and Calls the Driver.execute method
in = new Scanner(System.in);
System.out.println("(Client) Enter Server Ip to Connect to(Empty will give localhost):");
String ip = in.nextLine();
System.out.println("(Client) Enter your server port no:");
int port = in.nextInt();
if (ip == null || ip.length() == 0) {
ip = "localhost";
}
System.out.println("Connecting to " + ip + ":" + port);
// for taking input from client
// InputStream inputStream = connectionSocket.getInputStream();
// Try to connect to port and the IP address given on the command line.
try (Socket socket = new Socket(ip, port)) {
// for taking input from client
// InputStream inputStream = connectionSocket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader inputFromClient = new BufferedReader(inputStreamReader);
// for giving output to the client.
OutputStream outputStream = socket.getOutputStream();
// output to client, to send data to the server
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
// get output from server
InputStream serverInputStream = socket.getInputStream();
InputStreamReader inputStreamReaderFromServer = new InputStreamReader(
serverInputStream);
BufferedReader bufferReader = new BufferedReader(
inputStreamReaderFromServer);
//System.out.println("(Client) Give input:");
System.out.printf("Menu Options:\t\t\tCommands\n");
System.out.printf("-------------\t\t\t--------\n");
System.out.printf(" * 1 current Date & Time:\t1\n");
System.out.printf(" * 2 uptime: \t\t 2\n");
System.out.printf(" * 3 memory use: \t\t3\n");
System.out.printf(" * 4 Netstat: \t\t 4\n");
System.out.printf(" * 5 current users: \t\t5\n");
System.out.printf(" * 6 disk usage: \t\t6\n");
System.out.printf(" * 7 Quit: \t\t\t7\n\n");
String readingLineFromUser = inputFromClient.readLine();
// sending data to server
dataOutputStream.writeBytes(readingLineFromUser + "\n");
String getStringFromServer = bufferReader.readLine();
System.out.println("Got input from server (in client):" + getStringFromServer);
//attempts to get System Time
System.out.println("Requesting system time");
System.out.println("1");
//System.out.write("Server Date" + (new Date()).toString() + "\n");
System.out.println("Response from the server:\n");
// Read lines from the server and print them until "ServerDone" on
// a line by itself is encountered.
String answer;
while ((answer = inputFromClient.readLine()) != null && !answer.equals("ServerDone")) {
System.out.println(answer);
}
return;
}
}
}
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
public class Server {
private static ServerSocket severSocket;
private static Scanner in;
public static void main(String[] args) throws IOException {
in = new Scanner(System.in);
System.out.println("(Server) Enter your server port no:");
int port = in.nextInt();
System.out.println("Server Estabilsh Connection On Localhost or own ip with port : " + port);
severSocket = new ServerSocket(port);
System.out.println("Now you can run your client app.");
while (true) {
Socket connectionSocketListens = severSocket.accept();//Listens for a connection to be made to this socket and accepts it.
System.out.println("Accepted Client connection");
// for taking input from client
InputStream inputStream = connectionSocketListens.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader inputFromClient = new BufferedReader(
inputStreamReader);
// for giving output to the client.
OutputStream outputStream = connectionSocketListens.getOutputStream();
// output to client, to send data to the server
DataOutputStream dataOutputStream = new DataOutputStream(
outputStream);
// get output from server
String readingLineFromClientSocket = inputFromClient.readLine();
// sending data to client
String modified = doOperation(readingLineFromClientSocket);
// send data to client
dataOutputStream.writeBytes(modified + "\n");
// Read the request from the client! *** input = inputFromClient
String answer = inputFromClient.readLine();
System.out.println("Request from client "+answer);
Process cmdProc;
cmdProc = null;
// Execute the appropriate command.
if (answer.charAt(0) == '1') {
System.out.println("Responding to date and time request from the client ");
cmdProc = Runtime.getRuntime().exec("date");//MUST ADD TIME
}
if (answer.charAt(0) == '2') {
System.out.println("Responding to uptime request from the client ");
cmdProc = Runtime.getRuntime().exec("date");//MUST CHANGE
}
if (answer.charAt(0) == '3') {
System.out.println("Responding to memory use request from the client ");
cmdProc = Runtime.getRuntime().exec("date");
}
if (answer.charAt(0) == '4') {
System.out.println("Responding to Netstat request from the client ");
cmdProc = Runtime.getRuntime().exec("date");
}
if (answer.charAt(0) == '5') {
System.out.println("Responding to current users request from the client ");
cmdProc = Runtime.getRuntime().exec("date");
}
if (answer.charAt(0) == '6') {
System.out.println("Responding to disk usage request from the client ");
cmdProc = Runtime.getRuntime().exec("date");
}
if (answer.charAt(0) == '7') {
System.out.println("Responding to Quit request from the client ");
cmdProc = Runtime.getRuntime().exec("date");
}
else {
System.out.println("Unknown request ");
//need a socket.close or Server.close(); or something like that
return;
}
//Read the result of the commands and sent the result to the client one line at a time
// followed by the line "ServerDone"
BufferedReader cmdin = new BufferedReader(new InputStreamReader(cmdProc.getInputStream()));
String cmdans;
while ((cmdans = cmdin.readLine()) != null) {
System.out.println(cmdans);
}
System.out.println("ServerDone");
return;
}
}
private static String doOperation(String readingLineFromClientSocket) {
String[] array = readingLineFromClientSocket.split(" ");
StringBuilder strBuilder = new StringBuilder(array.length);
for (int i = array.length - 1; i >= 0; i--) {
String s = charReverse(array[i]);
strBuilder.append(s);
strBuilder.append(" ");
}
return strBuilder.toString();
}
private static String charReverse(String str) {
return new StringBuilder(str).reverse().toString();
}
}
I have a working version after making the following changes:
I changed this code in the Server class:
String answer = inputFromClient.readLine();
to
//String answer = inputFromClient.readLine();
String answer = modified;
System.out.println("Request from client "+answer);
Also all the lines like the following (apart from the first):
if (answer.charAt(0) == '2')
need to be
else if (answer.charAt(0) == '2')
and - on Windows at least - the following line:
cmdProc = Runtime.getRuntime().exec("date");
needs to be
cmdProc = Runtime.getRuntime().exec("cmd /c date /T");
This line:
while ((answer = inputFromClient.readLine()) != null && !answer.equals("ServerDone")) {
should be:
while ((answer = bufferReader.readLine()) != null && !answer.equals("ServerDone")) {
And after this line:
System.out.println(cmdans);
you need:
dataOutputStream.writeBytes(cmdans + "\n");

how to close a buffered reader when in mid communication

I need a bufferread to work with a client which closes when the word "CLOSE". THE client closes, I just can't get the sever to close once messages have been sent through it.
Heres what code I have:
`
import java.io.*;
import java.net.*;
class TCPClient2 {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser
= new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("143.53.30.136", 49250);//port number and ip address of client
DataOutputStream outToServer
= new DataOutputStream(clientSocket.getOutputStream());
InputStream sin = clientSocket.getInputStream();
// Just converting them to different streams, so that string handling becomes easier.
DataInputStream inFromServer = new DataInputStream(sin);
try {
do {
System.out.print("Enter message : ");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
//Question B4
//if statement for closing the socket connection
if (sentence.equals("CLOSE")) {
clientSocket.close();
//closes client socket
System.out.println("Socket Closed");
//prints socket closed to tell user socket has closed
System.exit(0);
}
outToServer.writeBytes(sentence + '\n');
System.out.print("Message sent! please wait for server message: ");
modifiedSentence = inFromServer.readUTF();
System.out.println("FROM SERVER: " + modifiedSentence);
} while (!sentence.equals("CLOSE"));
} catch (IOException e) {
}
clientSocket.close();
}
}`
AND the server:
`
/*
chris and paul
*/
import java.io.*;
import java.net.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TCPMultiThreadServer {
private static ServerSocket welcomeSocket;
//port number the server is using
private static final int PORT = 49250;
private static int clientNo =1;
public static void main(String argv[]) throws Exception
{
System.out.println("Opening port...\n");
try
{
// ServerSocket listens for new connections on specified port
welcomeSocket = new ServerSocket(PORT);
do
{
Socket client = welcomeSocket.accept();
System.out.println("\nNew client accepted.\n");
//Create a thread to handle communication with
//this client and pass the constructor for this
//thread a reference to the relevant socket...
TCPMultiThreadServer.ClientHandler handler =
new TCPMultiThreadServer().new ClientHandler(client,clientNo);
handler.start(); // Calls run() method in ClientHandler
clientNo++;
} while (true);
} catch (IOException e) {}
}
// Original work not credited
class ClientHandler extends Thread
{
private Socket client;
private BufferedReader inFromClient;
private BufferedReader text_to_Client;
private DataOutputStream outToClient;
private FileWriter Filestream;
private BufferedWriter out;
public int clientNo;
public boolean stopping;
//part A question 4, adding buffer string array to the program
private String[] buffer; //creation of buffer string array.
private int bufferI; // Index of the last thing inserted into the array
public ClientHandler(Socket socket, int clientNos)
{
//Set up reference to associated socket
client = socket;
clientNo= clientNos;
try
{
// Gets access to input/output stream of socket
inFromClient =
new BufferedReader(new InputStreamReader
(client.getInputStream()));
text_to_Client =
new BufferedReader(new InputStreamReader(System.in));
outToClient =
new DataOutputStream(client.getOutputStream());
} catch(IOException e) {}
}
public void run()
{
try
{
stopping = false;
//Question A4 buffer continued
buffer = new String[4];
//generates buffer string array containing 4 strings
bufferI = 0;
// make sure bufferIndex = 0
String clientSentence;
Thread mythread = Thread.currentThread();
do
{
//Accept message from client on socket's input stream
OutputStream sout = client.getOutputStream();
// Just converting them to different streams, so that string
// handling becomes easier.
DataOutputStream text_to_send = new DataOutputStream(sout);
clientSentence = inFromClient.readLine();
System.out.println("Message received from client number " +
clientNo + ": "+ clientSentence);
// String to be scanned to find the pattern.
String line = clientSentence;
String pattern = "[C][L][O][S][E]";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
//if (m.find( )) {
// System.out.println("Found value: " + m.find() );
// System.out.println("Found value: " + m.group(1) );
//System.out.println("Found value: " + m.group(2) );
//} else {
// System.out.println("NO MATCH");
//}
//part B question 4 close command
//if statement for closing the socket connection if it is equal to close
if(m.matches())
{ //prints socket closed to tell user socket has closed
System.out.println("Socket connection to client number "
+ clientNo + " closed");
try
{
} catch(Exception e) {}
out.flush();
out.close(); // Close the file handler
client.close(); // Close the connection with the client,
clientNo--; // Decrement the number of clients
}
else
{
//part A question 4, adding buffer string array to the program
// looks to see if the buffer string array is full
//and also looks to see if bufferIndex is in range
if (bufferI > buffer.length-1)
{
// Print BUFFER FULL
System.out.println("BUFFER FULL");
// Clear clientSentence string
clientSentence = " ";
// For loop which travels through the buffer array of string
for (int i=0; i<buffer.length; i++)
{
// Append buffer element to clientSentence string
clientSentence += buffer[i] + " , ";
buffer[i] = null; // makes the buffer null
}
bufferI = 0; // Reset bufferI back to 0 so writing to the buffer can restarted
// prints buffer cleared back to the clients
text_to_send.writeUTF("BUFFER CLEARED :" +
clientSentence);
}
else
{
buffer[bufferI] = clientSentence;
System.out.println("Buffer " + bufferI+ ": " +
buffer[bufferI]);
bufferI++;
System.out.println("Enter Message: ");
// Reads message from server interface
// and sends it to the client
clientSentence = text_to_Client.readLine();
text_to_send.writeUTF(clientSentence);
System.out.println("Your message: " +
clientSentence);
}
}
if (mythread.activeCount() == 2 &&
(clientNo ==0 || clientNo >0) &&
clientSentence.equals("CLOSE"))
{
System.exit(0);
}
} while(!clientSentence.equals("CLOSE"));
client.close();
} catch(IOException e) {}
}
}
}
`

While Loop not working as it should be

Client will request for a file, if the file exist in server then the server send the file and give a confirmation message. So i want to take input using the main while loop but it stops working after first iteration,
client side
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class WebClient {
public static void main(String[] args) throws Exception {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
String req;
System.out.println("Do you want to search? (Y/N): ");
Scanner user_input = new Scanner(System.in);
req = user_input.next();
while (req.equals("Y")) {
Socket clientSocket = new Socket("localhost", 2000);
System.out.println("Enter the file name: ");
String file = inFromUser.readLine();
DataOutputStream serverOutput = new DataOutputStream(clientSocket.getOutputStream());
serverOutput.writeBytes(file + '\n');
BufferedReader serverInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Text from the file: ");
while (true) {
String data = serverInput.readLine();
if (data == null) {
break;
}
System.out.println(data);
}
clientSocket.close();
System.out.println("Do you want to search again? (Y/N): ");
req = user_input.next();
}
}
}
server side
import java.io.*;
import java.net.*;
public class WebServer {
public static void main(String[] args) throws Exception
{
ServerSocket welcomeSocket = new ServerSocket(2000);
while (true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
String file = inFromClient.readLine();
System.out.println("Client Request: " + file); //Show The Client Request File
String path = ("E://From Varsity//4.2//Lab//Network Programming//Java trying//New TCP-Client+Server//tcp")+ "/" + file ;
File objfile = new File(path);
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
if (objfile.exists())
{
String readfile = rfile(path);
outToClient.writeBytes("\n" +readfile + "200 ok \n"); // when exact file find
}
else
{
outToClient.writeBytes("404 The Requested File not found \n"); // file not found
}
}
}
public static String rfile(String file_N) throws Exception
{
StringBuilder app = new StringBuilder();
BufferedReader bufferR = new BufferedReader(new FileReader(file_N));
try
{
String line = bufferR.readLine(); // read file from buffer
while (line != null) {
app.append(line); // append the line
app.append("\n");
line = bufferR.readLine();
}
}
finally
{
bufferR.close();
}
return app.toString();
}
}
Any help will be appreciated , thanks in advance
java.net.Socket is blocking. It'll block until it receives a close (the call to readLine() blocks until more data is available)
3 solutions:
Simplest: add outToClient.close() after the write.
Nonblocking: Use java.nio.SocketChannel/java.nio.ServerSocketChannel
Threaded: Create a new thread each time ServerSocket.accept() fires with the Socket object from accept.

Client socket doesn't take any input from cmd

I create a program where server sends a list of files to client which the client can then request to check the contents. It sends the list of files properly but then the client doesn't take any input from console.
This is the server program
import java.util.*;
import java.io.*;
import java.net.*;
class TCPServer{
public static void main(String args[]) throws Exception{
ServerSocket server = new ServerSocket(4888);
while(true){
Socket client = server.accept();
System.out.println(client);
DataOutputStream out = new DataOutputStream(client.getOutputStream());
File path = new File("C://testjava");
String[] files = path.list();
String send = "";
for(String file:files){
send = send + file + "\n";
}
out.writeBytes(send);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream ()));
String search_file = in.readLine();
String searching = "";
for(String file:files){
if (file.equals(search_file)){
searching = search_file;
}
}
if(searching.equals("")){
out.writeBytes("Requested file does not exist");
client.close();
}
Scanner file = new Scanner(new FileReader(searching));
while(file.hasNextLine()){
out.writeBytes(file.nextLine());
}
client.close();
}
}
}
This is the client program
import java.util.*;
import java.io.*;
import java.net.*;
class TCPClient{
public static void main(String args[]) throws Exception{
Socket client = new Socket("localhost",4888);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String display = "";
while ((display = in.readLine()) != null) {
System.out.println(display);
}
System.out.println("\nChoose a file");
Scanner src = new Scanner(System.in);
String ask_file = src.nextLine();
DataOutputStream out = new DataOutputStream(client.getOutputStream());
out.writeBytes(ask_file);
display = "";
while ((display = in.readLine()) != null) {
System.out.println(display);
}
}
}
Can anyone explain why the client isn't accepting any input?
Thanx
In the client, in.readLine() blocks until the Socket is closed.
Since you clearly don't want to close the socket yet, you could have the server send a special message to match for in the loop. When matched, break out of the loop.
Also, readLine/nextLine like methods gobble up newlines, so you need to add some like #EJP said. I edited your coded below. I tested it and it seems to be working now.
TCPServer
import java.util.*;
import java.io.*;
import java.net.*;
class TCPServer{
public static void main(String args[]) throws Exception{
ServerSocket server = new ServerSocket(4888);
while(true){
Socket client = server.accept();
System.out.println(client);
DataOutputStream out = new DataOutputStream(client.getOutputStream());
File path = new File("C://Users/Brian/Desktop");
String[] files = path.list();
String send = "";
for(String file:files){
send = send + file + "\n";
}
send = send + "END\n"; // ADD SOMETHING LIKE THIS ------------------------------>
out.writeBytes(send);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream ()));
String search_file = in.readLine();
String searching = "";
for(String file:files){
if (file.equals(search_file)){
searching = search_file;
}
}
if(searching.equals("")){
out.writeBytes("Requested file does not exist");
client.close();
}
Scanner file = new Scanner(new FileReader(searching));
while(file.hasNextLine()){
out.writeBytes(file.nextLine() + "\n"); // ADD A NEWLINE HERE ------------------>
}
client.close();
}
}
}
TCPClient
import java.util.*;
import java.io.*;
import java.net.*;
class TCPClient{
public static void main(String args[]) throws Exception{
Socket client = new Socket("localhost",4888);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String display = "";
// ADD A TEST FOR "END" HERE --------------------------------------------->
while ((display = in.readLine()) != null && !display.equals("END")) {
System.out.println(display);
}
System.out.println("\nChoose a file");
Scanner src = new Scanner(System.in);
String ask_file = src.nextLine() + "\n"; // ADD A NEWLINE HERE ----------->
DataOutputStream out = new DataOutputStream(client.getOutputStream());
out.writeBytes(ask_file);
display = "";
while ((display = in.readLine()) != null) {
System.out.println(display);
}
}
}
You're reading lines but you aren't writing lines. You need to add a \n to the strings you're writing with writeBytes(). Otherwise readLine() blocks forever waiting for a line terminator that never arrives.

Request Response Messages out of Sync UnExpected Behavior

The client
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class HTCPCPClient {
public static void main(String[] args) throws IOException {
HTCPCPClient client = new HTCPCPClient();
System.out.println("WELCOME TO THE COFFEE POT APPLICATION!");
client.startClient();
}
private void startClient() throws IOException {
final String HOST = "localhost";
final int PORT_NUMBER = 4444;
Socket clientSocket = null;
PrintWriter outToServer = null;
BufferedReader in = null;
String serverSentence = null;
String clientSentence = null;
BufferedReader inFromServer = null;
// create new socket
clientSocket = new Socket(HOST, PORT_NUMBER);
outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
do { // wait for 'QUIT'
// Create input stream
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
kbd = new Scanner(System.in);
clientSentence = null;
kbdInput = null;
System.out.println("Enter Method ( e.g. BREW )");
// next line of kbdInput from keybd.
kbdInput = kbd.nextLine().trim();
clientSentence = kbdInput + " coffee://127.0.0.1/pot-1 HTCPCP-new Accept-Additions: ";
clientSentence = clientSentence + "\nstart\n##";
// Send clientSentence to server
outToServer.println(clientSentence);
outToServer.flush();
System.out.println("\nMESSAGE FROM SERVER:");
do {
serverSentence = inFromServer.readLine();
System.out.println("\t" + serverSentence);
if (serverSentence.equals("##") == true) {
break;
}
} while (true);
// read and print message from server
} while (!clientSentence.contains("QUIT"));
// close connections
outToServer.close();
in.close();
inFromServer.close();
clientSocket.close();
}
}
Server Thread
import java.io.*;
import java.net.*;
public class HTCPCPClientWorker extends Thread {
Socket cwsocket = null;
public HTCPCPClientWorker(Socket cwsocket) {
super("ClientWorker");
this.cwsocket = cwsocket;
}
#Override
public void run() {
String clientSentence = null;
BufferedReader inFromClient = null;
PrintWriter outToClient = null;
try {
inFromClient = new BufferedReader(new InputStreamReader(cwsocket.getInputStream()));
outToClient = new PrintWriter(cwsocket.getOutputStream(), true);
} catch (IOException ex) {
System.err.println("Cannot create streams");
}
try {
do { // end when client says QUIT
StringBuffer clientInputLine[] = new StringBuffer[3];
clientInputLine[0] = new StringBuffer();
clientInputLine[1] = new StringBuffer();
// Get next message from client
for (int i = 0; i <= clientInputLine.length; i++) {
// read input line from BufferedReader
clientSentence = inFromClient.readLine();
// wait for EOF = ##
System.out.println("\tInput: " + clientSentence);
if (clientSentence.equals("##") == true) {
break;
}
clientInputLine[i].append(clientSentence);
if (clientSentence.contains("BREW")) {
outToClient.println("Message: " + clientSentence);
outToClient.println("HTCPCP-new 200 OK BREW START command completed.");
outToClient.println("Content-length: " + clientSentence.length());
outToClient.println("##");
outToClient.flush();
} else {
outToClient.println("Message: " + clientSentence);
outToClient.println("HTCPCP-new 400 Bad Request.");
outToClient.println("Content-length: " + clientSentence.length());
outToClient.println("##");
outToClient.flush();
}
} // end for loop
} while (!clientSentence.contains("QUIT"));
outToClient.println("GOODBYE!");
outToClient.flush();
System.out.println("\tClient has disconnected.");
cwsocket.close();
} catch (IOException e) {
e.printStackTrace();
}
} // end run
} end HTCPCPClientWorker.java
Client Console
WELCOME TO THE COFFEE POT APPLICATION!
Select an option:
1. Brew
2. Quit
1
Enter URL (e.g. BREW coffee://127.0.0.1/pot-1 HTCPCP-new )
BREW
MESSAGE FROM SERVER:
Message: BREW Accept-Additions:
HTCPCP-new 200 OK BREW START command completed.
Content-length: 23
##
Select an option:
1. Brew
2. Quit
1
Enter URL (e.g. BREW coffee://127.0.0.1/pot-1 HTCPCP-new )
BREW
MESSAGE FROM SERVER:
Message: start
HTCPCP-new 400 Bad Request.
Content-length: 5
##
Select an option:
1. Brew
2. Quit
Notice that the messages from the server are different despite the same URL being entered.
Any ideas where I'm going wrong?
In your server, you've got this on every iteration of your loop:
if (clientSentence.contains("BREW")) {
outToClient.println("Message: " + clientSentence);
outToClient.println("HTCPCP-new 200 OK BREW START command completed.");
outToClient.println("Content-length: " + clientSentence.length());
outToClient.println("##");
outToClient.flush();
} else {
outToClient.println("Message: " + clientSentence);
outToClient.println("HTCPCP-new 400 Bad Request.");
outToClient.println("Content-length: " + clientSentence.length());
outToClient.println("##");
outToClient.flush();
}
So the server will read "BREW" (etc), then spit out all that output, ending with ##. Your client displays all of that, and then asks for the next input... but the server won't have finished sending, because it will have read the next line of input, which is "start". It then prints out that second response, even though it's still reading the first request.
I suggest you finish reading the request then write out a response...
Note that your input loop should also have an exclusive upper bound, too:
for (int i = 0; i <= clientInputLine.length; i++) {
...
// This will blow up if i == clientInputLine.length
clientInputLine[i].append(clientSentence);

Categories