perdoname_
asked on
No response - Server [code attached]
Hello Experts,
I need your assistance about the following code which after the first message between the server and the client, server stops responding back to the client.
Thanks in advance for any kind of assistance !
I need your assistance about the following code which after the first message between the server and the client, server stops responding back to the client.
Thanks in advance for any kind of 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;
/**
* DOCUMENT ME!
*
* @author $author$
* @version $Revision$
*/
public class ClientServerMsg {
static final int LISTENING_PORT = 1025;
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;
@SuppressWarnings("unchecked")
Vector msgsList = new Vector();
Socket connection;
PrintWriter out = new PrintWriter(System.out, true); //For standard output
@SuppressWarnings("unused")
private OutputStream outstream;
ConnectionHandler(Socket conn) {
connection = conn;
start();
}
@SuppressWarnings("unchecked")
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 = null;
try {
instream = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
Scanner in = new Scanner(instream);
try {
outstream = connection.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
//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();
}
}
} finally {
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//Client:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
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 != null)
{
/* send the sentence to the server */
outToServer.writeBytes(sentence + '\n');
/* read response from the server */
modifiedSentence = inFromServer.readLine();
outToServer.flush();
}
clientSocket.close();
}
}
Your scanner is passing the value of the command through to the console without capturing it.
I think you meant to do this:
while("QUIT".equals(comman d) == false){
command = scanner.nextLine();
}
while("QUIT".equals(comman
command = scanner.nextLine();
}
... or in your case :
command = in.nextLine();
command = in.nextLine();
ASKER
that's not the problem
Because server accepts the first message and response but refuses to answer back to any further message
e.g
java Client
What host would you like to connect to?
localhost
What port would you like to connect to?
1025
Connecting to port 1025 of localhost....
Connection establised
POSTMESSAGE port
POSTMESSAGE something
READMESSAGE
java ClientServerMsg localhost 1025
Port: 1025
OK
Because server accepts the first message and response but refuses to answer back to any further message
e.g
java Client
What host would you like to connect to?
localhost
What port would you like to connect to?
1025
Connecting to port 1025 of localhost....
Connection establised
POSTMESSAGE port
POSTMESSAGE something
READMESSAGE
java ClientServerMsg localhost 1025
Port: 1025
OK
Running your code, the commands are not being captured.
ASKER
But that also happens even if i change while loop to that:
while("QUIT".equals(comman d) == false){
command = in.nextLine();
}
Any suggestions ?
while("QUIT".equals(comman
command = in.nextLine();
}
Any suggestions ?
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;
/**
* DOCUMENT ME!
*
* @author $author$
* @version $Revision$
*/
public class ClientServerMsg {
static final int LISTENING_PORT = 1025;
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;
@SuppressWarnings("unchecked")
Vector msgsList = new Vector();
Socket connection;
PrintWriter out = new PrintWriter(System.out, true); //For standard output
@SuppressWarnings("unused")
private OutputStream outstream;
ConnectionHandler(Socket conn) {
connection = conn;
start();
}
@SuppressWarnings("unchecked")
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 = null;
try {
instream = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
Scanner in = new Scanner(instream);
try {
outstream = connection.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
//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();
}
}
} finally {
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
In your client, you use the value of "sentence" in the while loop header, but capture another string - modeifiedsentence instead.
ASKER
Yes that's the response :S
Should be something else instead of that ?:S
Should be something else instead of that ?:S
ASKER
I tried to change the client code a little bit but still with no success
//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 != null)
{
/* send the sentence to the server */
outToServer.writeBytes(sentence + '\n');
outToServer.flush();
/* read response from the server */
modifiedSentence = inFromServer.readLine();
if (modifiedSentence != null)
{
outToServer.writeBytes(sentence);
}
outToServer.flush();
sentence = inFromUser.readLine();
}
clientSocket.close();
}
}
Hey! that's not the code you posted originally which was this
sentence = inFromUser.readLine();
while (sentence != null)
{
/* send the sentence to the server */
outToServer.writeBytes(sen tence + '\n');
/* read response from the server */
modifiedSentence = inFromServer.readLine();
outToServer.flush();
}
sentence = inFromUser.readLine();
while (sentence != null)
{
/* send the sentence to the server */
outToServer.writeBytes(sen
/* read response from the server */
modifiedSentence = inFromServer.readLine();
outToServer.flush();
}
ASKER
That's why i said:
"I tried to change the client code a little bit but still with no success"
"I tried to change the client code a little bit but still with no success"
For it to make any sense, you need to capture "sentence" inside your while loop.
ASKER
Such as that: ??
while (sentence != null)
{
sentence = inFromUser.readLine();
/* send the sentence to the server */
outToServer.writeBytes(sen tence + '\n');
/* read response from the server */
modifiedSentence = inFromServer.readLine();
outToServer.flush();
}
while (sentence != null)
{
sentence = inFromUser.readLine();
/* send the sentence to the server */
outToServer.writeBytes(sen
/* read response from the server */
modifiedSentence = inFromServer.readLine();
outToServer.flush();
}
Look, that should work but essentially you are not following best practices by having another readLIne() inside a routine that is dependent on the value of a different one. You should perhaps nest the while loops, or handle them in another fashion. It's one thing looking for errors in code, and another to rewrite it for you completely, which I am not prepared to do, I have to say.
Perhaps you can tell me what kind of communication you are hoping to arrange between the client and server? Just sketch in plain English your objectives.
Perhaps you can tell me what kind of communication you are hoping to arrange between the client and server? Just sketch in plain English your objectives.
ASKER
Thats the protocol i used to write the server:
A client posts messages to a server which adds them to a list of strings (which has a maximum length of 10 elements), or
queries messages from the server (imagine a helpdesk support application, where one client posts
user problems to a queue and another client retrieves these in order to deal with them).
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.
A client posts messages to a server which adds them to a list of strings (which has a maximum length of 10 elements), or
queries messages from the server (imagine a helpdesk support application, where one client posts
user problems to a queue and another client retrieves these in order to deal with them).
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.
//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;
@SuppressWarnings("unchecked")
Vector msgsList = new Vector();
Socket connection;
PrintWriter out = new PrintWriter(System.out, true); //For standard output
@SuppressWarnings("unused")
private OutputStream outstream;
ConnectionHandler(Socket conn) {
connection = conn;
start();
}
@SuppressWarnings("unchecked")
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 = null;
try {
instream = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
Scanner in = new Scanner(instream);
try {
outstream = connection.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
//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();
}
}
} finally {
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//Client:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class ClientMsg {
public static void main(String[] args) {
try
{
String fromserver,fromUser = null;
Socket client = new Socket(args[0], Integer.valueOf(args[1])); // hostname port
BufferedReader infromuser = new BufferedReader (new InputStreamReader(System.in));
BufferedReader infromserver = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter outtoserver = new PrintWriter(new OutputStreamWriter(client.getOutputStream()), true);
//while(fromUser!=null)
do {
fromUser=infromuser.readLine();
if (fromUser == null || fromUser.length() == 0) break;
outtoserver.println(fromUser);
fromserver = infromserver.readLine();
if (fromserver != null) {
System.out.println("Server sent " + fromserver);
}
}while (fromUser != null);
infromuser.close();
infromserver.close();
client.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
What do you mean by the client"querying messages from the server"? You receive messages, you don't query them
ASKER
Yes, receive messages and responds back appropriately.
SERVER
While ReceivedMessage = incomingBuffer.readLine() != QUIT
if ReceivedMessage.Header == REMOVEMESSAGE{
if MsgList.contains(ReceivedM essage)
sendClient(OK)
MsgList.remove(ReceivedMEs sage)
else
sendClient(ERROR)
continue
}
if ReceivedMessage.Header == READMESSAGE{
if MsgList.isEmpty() { sendClient(ERROR); continue }
if MsgList.containsKey("URGEN T")
msg = (Msg)MsgList.get("URGENT")
sendClient(msg);
MsgList.remove(msg)
continue
}
else{
sendClient((Msg)MsgList.ge tElement(0 ));
Msglist.remove(elementAt(0 ));
continue
}
if ReceivedMessage.Header == POSTMESSAGE{
if MsgList.size() <10
MsgList.add(ReceivedMessag e)
sendClient(OK)
continue
else{
sendClient(ERROR)
}
}
sendClient(OK);closeSocket (); shudown();
While ReceivedMessage = incomingBuffer.readLine() != QUIT
if ReceivedMessage.Header == REMOVEMESSAGE{
if MsgList.contains(ReceivedM
sendClient(OK)
MsgList.remove(ReceivedMEs
else
sendClient(ERROR)
continue
}
if ReceivedMessage.Header == READMESSAGE{
if MsgList.isEmpty() { sendClient(ERROR); continue }
if MsgList.containsKey("URGEN
msg = (Msg)MsgList.get("URGENT")
sendClient(msg);
MsgList.remove(msg)
continue
}
else{
sendClient((Msg)MsgList.ge
Msglist.remove(elementAt(0
continue
}
if ReceivedMessage.Header == POSTMESSAGE{
if MsgList.size() <10
MsgList.add(ReceivedMessag
sendClient(OK)
continue
else{
sendClient(ERROR)
}
}
sendClient(OK);closeSocket
Mirror that schematic for the client.
ASKER
But the protocol is already defined in the original code :S
Use any protocol you like (although your present one is a bit too long -READMESSAGE etc). My pseudo was meant as schematic for logic. You didn't follow that logic in your original question post code, and repeatedly changing it willy-nilly is the long way 'round getting to an answer.
Re-write your class accoridng to the aboce schema, and complement that schema in a client class. At that point, we'll be clear.
Re-write your class accoridng to the aboce schema, and complement that schema in a client class. At that point, we'll be clear.
*All* you have to do is to inject your existing executive statements inside the flow framework I've given. Just ensure the while - if - else pattern is followed. That's not too difficult, is it?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
In the server, there is a small typo. Replace this line :
for (int i = 0; i < msgsList.size()-1; i++) {
with this
for (int i = 0; i < msgsList.size(); i++) {
for (int i = 0; i < msgsList.size()-1; i++) {
with this
for (int i = 0; i < msgsList.size(); i++) {
ASKER
Thank you very much ! ! !
ASKER
Thank you very much ! ! ! !
Oh and in your server's readMessage method you need 'break;' statements after the ifs and else cases otherwise it'll print out all the matches.
Ok thanks. (Posts crossed) Read my last comment too. k.
ASKER
About the break statements:
do you mean in that way ?:
do you mean in that way ?:
void sendREADMESSAGE() throws Exception {
if (msgsList.size() == 0) {
out.println("ERROR");
break;
}
else if (msgsList.size() > 0) {
for (int i = 0; i < msgsList.size(); i++) {
if (((String) msgsList.elementAt(i)).startsWith("URGENT:")) {
out.println(((String) msgsList.elementAt(i)));
msgsList.remove(msgsList.elementAt(i));
break;
}
else {
out.println((String) msgsList.firstElement());
msgsList.remove(msgsList.firstElement());
break;
}
}
} else {
if (out.checkError()) {
throw new Exception("Error");
}
}
}
Yes, that's where I had them.
ASKER
Actually the first break creates an error so i let just the other two break statements
void sendREADMESSAGE() throws Exception {
if (msgsList.size() == 0) {
out.println("ERROR");
}
else if (msgsList.size() > 0) {
for (int i = 0; i < msgsList.size(); i++) {
if (((String) msgsList.elementAt(i)).startsWith("URGENT:")) {
out.println(((String) msgsList.elementAt(i)));
msgsList.remove(msgsList.elementAt(i));
break;
}
else {
out.println((String) msgsList.firstElement());
msgsList.remove(msgsList.firstElement());
break;
}
}
} else {
if (out.checkError()) {
throw new Exception("Error");
}
}
}
Oh no, sorry - I didn't see the first one! There's no need for that - it would indeed create an error. You only need them after the if and after the else, to stop iteration of the entire (matching) set.
You got it now.
You got it now.
ASKER
Once again thank you very much !
OK.
By the way, if you want a class that outputs System variables such as classpaths and other settings, there is one in my profile that you can copy for free.
k.
By the way, if you want a class that outputs System variables such as classpaths and other settings, there is one in my profile that you can copy for free.
k.
ASKER
Actually what im trying to do is to create a new database using sql and java
If you can be some help in my new questions about that it'd be grateful !
If you can be some help in my new questions about that it'd be grateful !
OK, well just post your questions, and I'll chip in if I can help. ;)