No response form Server Socket Java - 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");

Related

java IRC client file transfer

i'm stuck with a small problem that i can't solve .... i need to create an app in java that connects to irc server and have the ability to transfer a file to another client with in a specific channel. So i tried this below code and it doesnt work out,my problem is in making the socket to transfer the file. and at this given code i make the irc client to send you a file when you send a message "sendFile" to it, but it doesnt send the file named "any.txt" to the sender of the message. so what can i possibly do to transfer the file to the other client ??? .... and almost forgot ... when you try to send the command "sendFile" to the irc client, you must have a nickname "mer" without the "".
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.ServerSocket;
import java.io.File;
import java.io.FileInputStream;
import java.net.InetAddress;
public class MainTest {
private static String nickUse;
public static void main(String args[]) throws Exception{
// The server to connect to and our details.
File fileIn = new File("any.txt");
String server = "localhost";
String nick = "testJava";
String login = "anyName";
// The channel which the bot will join.
String channel = "#here";
// Connect directly to the IRC server.
ServerSocket serverSoc = new ServerSocket(0);
Socket socket = new Socket(server, 6667);
InetAddress intetAdd = socket.getInetAddress();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream( )));
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream( )));
// Log on to the server.
writer.write("NICK " + nick + "\r\n");
writer.write("USER " + login + " 8 * : This is a channel\r\n");
writer.flush( );
// Read lines from the server until it tells us we have connected.
String line = null;
while ((line = reader.readLine( )) != null) {
if (line.indexOf("004") >= 0) {
// We are now logged in.
break;
}
else if (line.indexOf("433") >= 0) {
System.out.println("Nickname is already in use.");
return;
}
}
// Join the channel.
writer.write("JOIN " + channel + "\r\n");
writer.flush( );
// Keep reading lines from the server.
while ((line = reader.readLine( )) != null) {
if (line.startsWith("PING ")) {
// We must respond to PINGs to avoid being disconnected.
writer.write("PONG " + line.substring(5) + "\r\n");
writer.flush();
System.out.println("THis is the line recieved when server sends a ping verification "+line);
}
else {
// Print the raw line received by the bot.
System.out.println(line);
if(line.contains(":") && line.contains("!")){
int positionOfIni = line.indexOf(":");
int lastOf = line.indexOf("!");
String nickComm = line.substring(positionOfIni+1,lastOf);
if(!nickComm.equalsIgnoreCase("mer")){
nickUse = nickComm;
}
}
if(nickUse!=null && line.endsWith(nickUse) == false){
int messagePo = line.lastIndexOf(":");
System.out.printf("%s %s %s\n",nickUse,"Says:",line.substring(messagePo+1));
nickUse = null;
}
if(line.endsWith("sendFile")){
byte[] add = intetAdd.getAddress();
writer.write("PRIVMSG " + "mer" +" :\u0001"+ "DCC SEND "+fileIn.getName()+" "+ipToLong(add)+" "+serverSoc.getLocalPort()+" "+fileIn.length()+"\u0001");
writer.flush();
Socket serSoc = serverSoc.accept();
serSoc.setSoTimeout(30000);
serverSoc.close();
BufferedOutputStream output = new BufferedOutputStream(serSoc.getOutputStream());
BufferedInputStream input = new BufferedInputStream(serSoc.getInputStream());
BufferedInputStream finput = new BufferedInputStream(new FileInputStream(fileIn));
byte[] outBuffer = new byte[1024];
byte[] inBuffer = new byte[4];
int bytesRead = 0;
while ((bytesRead = finput.read(outBuffer, 0, outBuffer.length)) != -1) {
output.write(outBuffer, 0, bytesRead);
output.flush();
input.read(inBuffer, 0, inBuffer.length);
Thread.sleep(4);
}
}
}
}
}
public static long ipToLong(byte[] address) {
if (address.length != 4) {
throw new IllegalArgumentException("byte array must be of length 4");
}
long ipNum = 0;
long multiplier = 1;
for (int i = 3; i >= 0; i--) {
int byteVal = (address[i] + 256) % 256;
ipNum += byteVal*multiplier;
multiplier *= 256;
}
System.out.println(ipNum);
return ipNum;
}
}
i just conclude the answer of having not to transfer with the help of IRC server. but instead i just create it's own server, that is capable of receiving files (Encrypted).

Client to Server Messaging- Java

I would like some input on my relatively simple Client to server messaging program.
I think the Client part is OK, but the server bit is a bit broken.
The program actually sort of works (client can send messages to server).
I am having trouble putting a username + password on it (set it up for a default password + username , not storing multiple usernames + password) (currently using username:1, password:2).
And I would like for the server the receive the clients Ip, when it connects, if anyone has any spare time and some java experience it would be greatly appreciated.
Client:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
class LongClient {
public static void main(String args[]) {
try {
Socket skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
Scanner kbReader = new Scanner(System.in);
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
out.flush();
String message, servermessage;
InetAddress clientip = InetAddress.getLocalHost();
System.out.println("Preparing to chat...");
out.println("Client IP Address: " + clientip); // sends message to client giving ip
out.println("Client hostname: " + clientip.getHostAddress()); // send message to client giving computer name
do {
if (in.ready()) {
servermessage = in.readLine();
System.out.println("server>: " + servermessage);
}
message = kbReader.nextLine();
out.println(message);
out.println("Done");
//message="bye";
//out.println("bye");
Thread.currentThread().sleep(300);
} while (!message.equals("bye"));
out.close();
in.close();
} catch(Exception e) {
System.out.print(e);
}
}
}
Server:
import java.lang.*;
import java.io.*;
import java.net.*;
class LongServer {
public static void main(String args[]) throws IOException {
String data = "Welcome to My Server"; //welcome message
String data1 = "enter username"; //welcome message
String message;
int idstats1 = 0; //verifyed username
int idstats2 = 0; //verifyed password
int verify1 = 0;
try {
//Detecting the localhost's ip address
InetAddress localaddr = InetAddress.getLocalHost();
System.out.println ("Local IP Address : " + localaddr );
System.out.println ("Local hostname : " + localaddr.getHostAddress());
//Creating a server socket for connection
ServerSocket srvr = new ServerSocket(1234);
System.out.println("Waiting for connection on "+localaddr);
//Accept incoming connection
Socket skt = srvr.accept();
System.out.print("Server has connected!\n");
//get Input and Output streams
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
System.out.print("Sending string: '" + data + "'\n");
out.println(data); //sends welcome message
System.out.print("Sending string: '" + data1 + "'\n");
out.println(data1); //sends welcome message
message = in.readLine(); //reads the line typed in
while(verify1 == 0) {
if (idstats1 == 0) {
//if the client is not verifyed, it asks for a password
out.println("enter username");
}
if (idstats2 == 0) {
//if the client is not verifyed, it asks for a password
out.println("enter password");
}
if (message.equals("1")) {
//is the input is password, then the client is verifyed
out.println("Username accepted");
idstats1 = 1;
}
if (message.equals("2")) {
//is the input is password, then the client is verifyed
out.println("Password Accepted");
idstats2 = 1;
}
if (idstats1 == 1 && idstats2 == 1) {
verify1 = 1;
}
}
if (verify1 == 1) {
//if client is verifyed, it asks them to type a message and prints it to the console
out.println("enter a message");
System.out.println("client>"+message);
}
if (message.equals("bye")) {
//if the client enters "bye" then the server closes
out.println("Server closing");
System.out.println("server>Server closing");
}
while(!message.equals("bye")); {
out.close();
skt.close();
srvr.close();
}
} catch(BindException e) {
e.printStackTrace();
System.out.print("A server is already running on the same port.");
} catch(SocketException e) {
e.printStackTrace();
System.out.print("Client has disconnected rudely.");
} catch(Exception e) {
e.printStackTrace();
System.out.print(e);
}
}
}
Thanks, any help would be appreciated.

Where to place my loop for better results in Client-Server architecture in Java?

I have a client server architecture in Java in which I need to place a loop.
I've spent some time to think about where to put this loop, but anywhere I tried it did not get the result expected.
Here is my client.java :
public class Client {
private static Scanner scanner;
public static void main(String[] args) throws IOException {
scanner = new Scanner(System.in);
// set up server communication
Socket clientSocket = new Socket(InetAddress.getLocalHost(), 1234);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
System.out.println("Enter pin : ");
String password = scanner.next();
// send PIN to server
out.println(password);
out.flush();
// get response from server
String response = in.readLine();
System.out.println(response);
scanner.close();
in.close();
out.close();
clientSocket.close();
}
}
Here is my server.java :
public class Server {
private static ServerSocket server;
public static void main(String[] args) throws Exception {
server = new ServerSocket(1234);
Socket socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
// Listen for client requests:
String request = in.readLine();
while (request != null) {
// check PIN, send result
boolean pinCorrect = checkPin(request);
out.println(pinCorrect ? ":)" : ":(");
out.flush();
}
out.close();
in.close();
socket.close();
}
}
I need to repeat this process if the user does not enter exactly 4 digits, so I've been thinking of a do{}while(pinSize != 4) loop.
But when I place it in the Server I always have the wrong output ":)" or ":(" instead of just "Pin must be 4 digits", then I tried to put in the Client part, but this time I always had the possibility to enter only one pin so the loop did not work that much.
Actually this is some code I would put into my loop:
if (pinSize != 4) {
System.out.println("Pin must be 4 digits");
} else {
System.out.println("Checking...");
}
Any ideas ? Thanks.
Put the check in client side code. For more info read inline comments.
Fist use nextLine() in place of next() to read a whole line at a time.
Validation check for password along with its length check
Here is the modified client side code. Please incorporate the changes.
...
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
System.out.println("Enter pin : ");
String password = null;
// 4 digits pattern
Pattern p = Pattern.compile("\\d{4}");
while (true) {
password = scanner.nextLine();
int pinSize = password.length();
if (pinSize == 4) {
Matcher m = p.matcher(password);
if (m.find()) {
System.out.println("Checking " + password);
break;
} else {
System.out.println("Pin must be 4 digits");
}
} else {
System.out.println("Pin must be 4 digits");
}
}
// send PIN to server
out.println(password);
...

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

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());

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