Avatar of perdoname_
perdoname_
 asked on

removemessage + readmessage / Client-Server app [problem with code]

Hello Experts,

I need your assistance about the following errors of a client/server application:

My current problem is that server reads the POSTMESSAGE command responds OK but in the case of READMESSAGE server doesn't give an answer back till it gets another command from the client

Also in the case of REMOVEMESSAGE it prints just ERROR.

---------------
Protocol:

Client’ Server:  POSTMESSAGE message 
Server’Client: If the list is not full, append message to the list and respond OK to the client.
Otherwise, respond ERROR  
 
Client’ Server: READMESSAGE  
Server’Client: If the list is empty, send ERROR. Otherwise: in case any of the messages in the list
(it doesnt matter which one) starts with URGENT:, send this message to the client and remove it
from the list. Otherwise, send the first message in the list to the client and remove it from the list.  
 
Client’ Server: REMOVEMESSAGE message 
Server’Client: If message is not contained in the list, send ERROR. Otherwise, remove it from
the list and send OK to the client.  
 
Client’ Server: QUIT  
Server’Client: Respond OK to the client and close the socket used to communicate with the
client.



Thanks in advance for any assistance !!
//Server:
 
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
 
import java.net.ServerSocket;
import java.net.Socket;
 
import java.util.Scanner;
import java.util.Vector;
 
 
 
public class ClientServerMsg {
	static final int LISTENING_PORT = 4055;
 
	public static void main(String[] args) throws Exception {
		ServerSocket listener;
		listener = new ServerSocket(LISTENING_PORT);
		System.out.println("Port: " + LISTENING_PORT);
 
		while (true) {
			Socket connection = listener.accept();
			new ConnectionHandler(connection);
		}
	}
 
	static class ConnectionHandler extends Thread {
		int MAX = 10;
		Vector msgsList = new Vector();
		Socket connection;
		PrintWriter out = new PrintWriter(System.out, true); //For standard output
		private OutputStream outstream;
 
		ConnectionHandler(Socket conn) {
			connection = conn;
			start();
		}
 
		void sendPOSTMESSAGE(String msg) throws Exception {
			try {
				if (msgsList.size() < MAX) {
					msgsList.addElement(msg);
					out.println("OK");
					out.flush();
				} else {
					out.println("ERROR");
					out.flush();
				}
			} catch (Exception ex) {
				out.println("ERROR");
				out.flush();
			}
 
			if (out.checkError()) {
				throw new Exception("Error while receiving the message");
			}
		}
 
		void sendREADMESSAGE() throws Exception {
			if (msgsList.size() == 0) {
				out.println("ERROR");
				out.flush();
			} else if (msgsList.size() > 0) {
				for (int i = 0; i < msgsList.size(); i++) {
					if (((String) msgsList.elementAt(i)).startsWith("URGENT:")) {
						out.write((String) msgsList.elementAt(i));
						msgsList.remove(i);
					} else {
						out.write((String) msgsList.elementAt(0));
						msgsList.remove(0);
					}
				}
			} else {
				if (out.checkError()) {
					throw new Exception("Error");
				}
			}
		}
 
		void sendREMOVEMESSAGE(String remvmsg) throws Exception {
			for (int i = 0; i < msgsList.size(); i++) {
				if (((String) msgsList.elementAt(i)).equals(remvmsg)) {
					msgsList.remove(i);
					out.println("OK");
					out.flush();
				} else {
					out.println("ERROR");
					out.flush();
				}
			}
		}
 
		void sendQUIT() throws Exception {
			out.close();
			connection.close();
		}
 
		public void run() {
			String command = "";
			try {
				InputStream instream = connection.getInputStream();
				Scanner in = new Scanner(instream);
				outstream = connection.getOutputStream();
 
				//command = in.nextLine();
				while ("QUIT".equals(command) == false) {
					if (in.hasNextLine()) {
						command = in.nextLine();
					}
 
					if (command.startsWith("POSTMESSAGE")) {
						try {
							sendPOSTMESSAGE(command);
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else if (command.equals("READMESSAGE")) {
						try {
							sendREADMESSAGE();
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else if (command.startsWith("REMOVEMESSAGE")) {
						try {
							sendREMOVEMESSAGE(command);
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else if (command.equals("QUIT")) {
						try {
							sendQUIT();
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else {
						out.println("UNKNOWN COMMAND");
						out.flush();
					}
				}
			}catch(IOException e) {
				e.printStackTrace();
			} finally {
				try {
					connection.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
 
}
 
 
 
 
//Client:
 
//Client:
 
import java.io.*;
import java.net.*;
 
public class Client {
 
	public static void main(String argv[]) throws Exception
	{
		String sentence;
		String modifiedSentence = null;
		String hostname;
		int portNumber;
		String portString;
 
		BufferedReader inFromUser =
			new BufferedReader(new InputStreamReader(System.in));
		System.out.println("What host would you like to connect to?");
		hostname = inFromUser.readLine();
 
		System.out.println("What port would you like to connect to?");
		portString = inFromUser.readLine();
 
		portNumber = Integer.parseInt(portString);
 
		System.out.println("Connecting to port "+ portNumber+ " of "+ hostname +"....\n");
		Socket clientSocket = new Socket(hostname, portNumber);
 
		DataOutputStream outToServer =
			new DataOutputStream(clientSocket.getOutputStream());
 
		BufferedReader inFromServer =
			new BufferedReader(new
					InputStreamReader(clientSocket.getInputStream()));
 
		System.out.println("Connection establised");
 
        //sentence = inFromUser.readLine();
        while (!(sentence = inFromUser.readLine()).equalsIgnoreCase("QUIT"))
        {
              /* send the sentence to the server */
              outToServer.writeBytes(sentence + '\n');
             
              // this line prevents the next message from user
              //modifiedSentence = inFromServer.readLine();
             
              outToServer.flush();
        }
 
 
 
		clientSocket.close();
 
	}
}

Open in new window

JavaProgramming Languages-Other

Avatar of undefined
Last Comment
krakatoa

8/22/2022 - Mon
krakatoa

You have the same question open already, wherein I suggested a new schematic for this.
ASKER CERTIFIED SOLUTION
CEHJ

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
CEHJ

...and, i don't know how many times i've said not to use DataOutputStream in the client but to use PrintWriter. Your problem disappears for me after the two fixes i've mentioned
SOLUTION
krakatoa

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
perdoname_

ASKER
But its not the same problem as before
Server now responds back to many messages:
ava ClientServerMsg localhost 4055
Port: 4055
OK
POSTMESSAGE messageOK
ERROR
ERROR


java Client
What host would you like to connect to?
localhost
What port would you like to connect to?
4055
Connecting to port 4055 of localhost....

Connection establised
POSTMESSAGE message
READMESSAGE
POSTMESSAGE msg
REMOVEMESSAGE POSTMESSAGE messageOK
REMOVEMESSAGE POSTMESSAGE message


This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
perdoname_

ASKER
@CEHJ:
Thank you. READMESSAGE is solved


Any ideas about the sendREMOVEMESSAGE method?
CEHJ

What's going wrong with that?
perdoname_

ASKER
For example:

//Client
POSTMESSAGE ok
REMOVEMESSAGE ok


and Server respodns back OK for the POSTMESSAGE but ERROR for the REMOVEMESSAGE
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
krakatoa

ok - I've re-done your code so it works. I can post it over in the original question, but you'd need to deposit the points there for me, and of course it goes without saying for the help the other expert(s) gave you in this one. OK?
perdoname_

ASKER
krakatoa

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
krakatoa

And I'll answer this point : ID:21324055Author:perdoname_

here when we've done that.

(But I don't expect any points what I say in this question / post)
perdoname_

ASKER
But only you have posted in that question so there is no problem with the points
krakatoa

OK - so your classes are about to appear over there.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
krakatoa

(Of course I hope you saw from all this that your messages were being stored along with their protocols as well, making it extremely confusing). Thanks. k.