Input Problem with Java Socket - java

I am trying to do a programming exercise here making a client and a server that work with sockets.For the communication between them i use PrintWriter and InputReader.What im stuck with is : How can i check if the Server is trying to send something to the client,while the client is waiting for input ? At this point the client loop is something like this :
do {
outToServer.println(inFromUser.readLine());
String fromServer=inFromServer.readLine();
if(fromServer.equals("OK")){
clientSocket.close();
}else{
System.out.println(fromServer);
}
} while (!clientSocket.isClosed());
The problem is that in some cases the server needs to print multiple lines ,before needed an input again.Instead it prints 1 line then ill have to type something,then another line comes etc . Is there a way to get around that problem ? Thanks .

So you're going to need to encapsulate the
outToServer.readLine();
in a while loop that has a boolean conditional similar to a hasNext() function. You may want to set it up as follows:
String x = outToServer.readLine();
//while x doesn't equal whatever readLine would return if there's nothing to read
//I'm not sure if this is a null String or not
while(x!=null){
System.out.print(x);//print it however you wish
String x = outToServer.readLine();
}
And then do something similar for inFromServer if needed.

Related

Method does nothing if called within an if, if called directly from on event it works

I`m building a discord bot with jda, made a method to use mXparser to get a math operation as an input from the chat e.g: /math 5+1
wrote everything to get the message, separate the arguments from the input on the chat, everything works until I put the code inside an IF statement that checks if it actually starts with "/math", the code inside it uses mXparser to calculate everything and send it back to chat.
Tried just about everything I could think of, taking all variables off the method, rewriting everything, I don`t get any errors either as stack trace or in the code editor, it just doesnt go through, tried just printing everything and it works fine as well, printing all the values on the console, everything seems to be right.
This part is where I check for the message, get the Strings and trim everything
public void onMessageReceived(MessageReceivedEvent event) {
this.messageReceived = event;
this.prefix = Main.prefix;
checkPrefix = messageReceived.getMessage().getContentRaw().split("\\s" + prefix);
mainArg = checkPrefix[0];
checkArgs = messageReceived.getMessage().getContentRaw().split(" ");
callAllCommands();
}
Here is the command to take the actual expression from the chat input calculate it and send it back.
private void mathCommand() {
mathexp = new Expression(checkArgs[1]);
messageReceived.getChannel().sendTyping().queue();
essageReceived.getChannel().sendMessage(Double.toString(mathexp.calculate())).queue();
}
This is inside the callAllCommands() method, that is how it is supposed to work, if the command on the chat is /math then the expression e.g: /math 1+1 it will send the result back, if I take off the IF statement it works just fine but then I can't check for the command. The other commands do work fine with the IF statement
if (mainArg.contentEquals(prefix + "math")) {
mathCommand();
}
I don't really get any errors, it just does not work, sorry if I missed something really simple, i`m not that experienced yet.

How to run code example chat in chapter 2 ebook Java Message Service?

How can run chat.class in chapter 2 ebook Java Message Service?
code here
I can't run main method Although i add javax.jms still can't run
/* Run the Chat client */
public static void main(String [] args){
try{
if(args.length!=3)
System.out.println("Topic or username missing");
// args[0]=topicName; args[1]=username; args[2]=password
Chat chat = new Chat(args[0],args[1],args[2]);
// read from command line
BufferedReader commandLine = new
java.io.BufferedReader(new
InputStreamReader(System.in));
// loop until the word "exit" is typed
while(true){
String s = commandLine.readLine();
if(s.equalsIgnoreCase("exit")){
chat.close(); // close down connection
System.exit(0);// exit program
}else
chat.writeMessage(s);
}
}catch(Exception e){ e.printStackTrace(); }
}
}
error
Topic or username missing
java.lang.ArrayIndexOutOfBoundsException: 0
at chap2.chat.Chat.main(Chat.java:97)
Seems you're quite new to Java.
First, notice that the message you get ("Topic or username missing") comes from the code itself, so the code is running.
Look where this comes from: it is printed because args.length is not equal to 3. When you run a Java class from the command line, the parameters are passed into the args array. So, you should have provided enough parameters.
That should solve the direct problem. Below the line, I'd like to explain a bit more.
The error message
java.lang.ArrayIndexOutOfBoundsException: 0
at chap2.chat.Chat.main(Chat.java:97)
is quite clear: it goes wrong in line 97 of Chat.java. In the main method.
If you see this, you should look in your code for that line (most IDE's tell you the line number, if you know where to look).
When you post a question here on SO (or anywhere), and have a stack trace
with a line number, it is good practice to point out which line the line number refers to. That helps those who read your question to better understand the problem.
An ArrayIndexOutOfBoundsException means that you have an array index that is pointing outside the array.
I have a hunch that the line in question is this one:
Chat chat = new Chat(args[0],args[1],args[2]);
In this case the index value is 0, as we can see in the error message. It may be a bit confusing for a beginner, but args[0] is the first value in your array. (args[1] is the second, args[2] the third, and so on).
So if 0 is already out of the bounds of the array... that means your array doesn't even have a first value. It has 0 values.
The error then results from Java trying to read the first element of an array that has 0 elements. The solution is to:
either make sure that the array has enough values
or provide an error message and stop executing that part of the code.
This example is a bit sloppy because it did provide an error message, but then continued to execute the code until it broke.

Java (Android) doesn't understand \n captured through a tcp stream

I have a problem with writing down the data I recieve through my C# server in an Android app. The app sends the server the function to give back a list of all running processes.
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
sw.Write(p.ProcessName + "\n");
sw.Flush();
Console.Write(p.ProcessName + "\n");
}
The Console output works perfectly fine, but at the recieving end I just get the first process in the list. The problem lies in the \n: I tried first building up a string, then flushing and with for-loops printing numbers. It's always the \n that fails.
I'm printing in out into a TextView, if that helps.
Thanks for any suggestions.
Instead of sending "\n" to your client send "%d%n%s%n" Source: \n won't work, not going to a new line
Last option would be instead of sending the "\n" from the server you could write a byte and then on the android side you could interpret it as
a "\n"
if(DataInputStream.readByte()==1){//Replace the 1 with whatever byte you want to represent the \n.
runOnUiThread(new Runnable(){//Runs the code on the UiThread
public void run()
{
MainActiviy.TextView.append("\n");//When you get the byte you append a \n to your textview
}
});
}
You would run this piece of code on a Network thread and it would update the Ui.

Networked GUI handler for binary protocol

Alright, so I created a Client and Server that manipulates a Map via a GUI interface using a text based protocol. The handler below was used to create a "work order" to manipulate the GUI on a separate thread from the network communications.
class RemoteInputHandler implements Runnable,SharedVariables
{
#Override
public void run()
{
try
{
String input = netComm.reader.readLine();
while (input != null)
{
// Make a separate copy of the input string
String inputCopy = input;
// Post a work order to process the command on the GUI thread
Platform.runLater(() ->
{
handleRemote(inputCopy);
});
// Get the next remote input
input = netComm.reader.readLine();
}
} catch (IOException ex)
{
throw new RuntimeException(ex);
}
}
This pulls the next line of input from the server without freezing up the GUI. I then use the input in the handleRemote() method with a scanner to determine what is done with the input. The string retrieved from the reader looked something like "put key value". I'd then get the first word "put", using a scanner, to get the "command" and use a switch statement to determine how the GUI / Map should be updated on the client and server side respectively.
I'm doing another GUI based program that uses a binary protocol instead, but I'm having trouble figuring out how to handle the information in the same way as I did with the readLine() above. Is there a way to do this? Am i thinking about it the wrong way? I thought I could just get all of the bytes into an array, but I'm having trouble even figuring that out.
I could really use a hint! Thank you!

how to write simple txt testcases in java

Hi I'm writing my first Java app and I've got a few Testcases (*.tc files) I want to direct to the app via this script:
for f in `ls *.tc`; do
echo "Current Testcase: $f"
x=${f%.*}
java Main < $x.tc > $x.out
if diff "$x.out" "$x.should"; then
echo "passed testcase $f"
let PASSED=PASSED+1
else
echo "failed testcase $f"
let FAILED=FAILED+1
fi
done
The Problem is I can't quite figure out why as soon as the tc file contains more than one line the app goes nuts. For example: quit.tc contains
quit
and works just like when I manually enter "quit", therfore the testcase passes.
However when I write another tc: quit2.tc which contains
lala
test
quit
The app quits after the first command (because the readString function seems to return null afterwards).
Here is the function responsible for reading:
public String readString(){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String answer = null;
try {
answer = br.readLine();
return answer;
}
catch(IOException ioe) {
System.out.println("IO Error");
}
return answer;
}
I dont know why or when this function returns null when I redirect to the app, which seems to be the problem. Can you help out so I can get the tc script working? thx
If you're new to java, and you still shape your style and way of doing things, I will recommend you 2 tips:
1) use Scanner to read your input. Using nextLine() method of the Scanner object is probably what you're looking for.
2) design your code, so that it's testable via JUnit.
Still, in your readString() method, remove the return answer; from the try block.
UPDATE: try to implement the following in your function:
a) while the scanner instance hasNextLine() is true ->
b) call scanner instance nextLine() method ->
c) parse the line, and see if it equals 'quit' ->
d) implement the corresponding logical if cases.
Your problem is BufferedReader: It will read the whole file at once (for performance reasons).
Since you create a new BufferedReader each time readString() is called, the first reader will swallow most of the file (or all of it) and the second reader will hit end-of-file.
The solution is to put the reader into a field, create it once and then always use the same reader to call readLine()
Plus you never close the reader.
Java will forget unused objects but you must properly close OS resources like FileInputStreams

Categories

Resources