Java While Loop - java

I'm having some issues with a while loop. This while loop is run in a thread, and is the "main loop" of the thread, and I'm having issues with it not continuing if one of the if statements it loops over is false. This thread handles both sending and receiving IRC Commands/Messages for use in a minecraft client.
The code as it stands is below:
do {
System.out.println("IRC Thread Looped!");
if(tosend != "") {
writer.write("PRIVMSG " + channel + " :"+tosend+"\r\n");
System.out.println(tosend);
mc.thePlayer.addChatMessage("\247f[\247bIRC\247f] \2477"+nick+": \247f"+tosend);
tosend = "";
writer.flush();
}
if((line = reader.readLine()) != null) {
if(line.startsWith("PING ")) {
writer.write("PONG " + line.substring(5) + "\r\n");
writer.flush( );
}
else {
// we need to pretty this ugly sh*t up!
try {
String parsedline;
String args[] = line.split("!");
String args2[] = args[1].split(":");
args[0] = args[0].substring(1, args[0].length());
parsedline = "\2477"+ args[0] +": \247f"+ args2[1];
mc.thePlayer.addChatMessage("\247f[\247bIRC\247f] "+parsedline);
}
catch(Exception e) {
mc.thePlayer.addChatMessage("\247f[\247bIRC\247f]\247f "+line);
continue;
}
}
}
try {
Thread.sleep(90L);}catch(Exception e) { };
}
} while(true);

Note that java threads like to eat exceptions that get thrown out of the run() method.
Since you have IO such as if((line = reader.readLine()) != null){ not in a try/catch, you might be throwing an exception and exiting.
What I like to do with threads is to put the main thread code in runImpl() and have the run() look like this.
public void run()
{
try
{
runImpl();
}
catch( Throwable t )
{
// log the throwable
}
}
Then at a minimum you can discover that your thread threw something unexpected.

If the problem is caused by getLine() blocking behavior you could probably fix it this way. I haven't run that code so I don't guarantee it will work. Also make sure that reader is a BufferedReader.
StringBuilder sb = new StringBuilder();
String line = null;
int n = 0;
do {
System.out.println("IRC Thread Looped!");
if(tosend != ""){
writer.write("PRIVMSG " + channel + " :"+tosend+"\r\n");
System.out.println(tosend);
mc.thePlayer.addChatMessage("\247f[\247bIRC\247f] \2477"+nick+": \247f"+tosend);
tosend = "";
writer.flush();
}
while (reader.ready()) {
int c = reader.read();
if (c == -1) {
if (n > 0) {
line = sb.toString();
sb = new StringBuilder();
}
break;
}
if (c == '\n' || c == '\r') {
line = sb.toString();
sb = new StringBuilder();
break;
}
sb.append((char)c);
n++;
}
if(line != null){
if (line.startsWith("PING ")) {
writer.write("PONG " + line.substring(5) + "\r\n");
writer.flush( );
}
else
{
//we need to pretty this ugly shit up!
try{
String parsedline;
String args[] = line.split("!");
String args2[] = args[1].split(":");
args[0] = args[0].substring(1, args[0].length());
parsedline = "\2477"+args[0] +": \247f"+ args2[1];
mc.thePlayer.addChatMessage("\247f[\247bIRC\247f] "+parsedline);
}catch(Exception e){
mc.thePlayer.addChatMessage("\247f[\247bIRC\247f]\247f "+line);
continue;
}
}
line = null;
n = 0;
}
try{Thread.sleep(90L);}catch(Exception e){};
} while(true);

Related

java.net.SocketException: Connection reset by peer. In custom twitch bot

I created custom Twitch bot with using of cavariux library. I called this methods in main class.
bot.setOauth_Key("oauth:key_Value");
bot.connect();
bot.joinChannel(channel.toString());
bot.start();
Approximately one of the 5-6 launches of the bot is accompanied by an exception
java.net.SocketException: Connection reset by peer
. The stack trace indicates that the exception starts on this line.
while ((line = this.reader.readLine( )) != null && !stopped)
in TwitchBot class in method start(). I didn't change code of this library except adding utf encoding in method connect(String ip, int port).
this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
I've tested my bot on different PCs. On some machines I don't have this issue. On some I got this exception more often.
This is code of method start() in TwitchBot class.
public final void start()
{
if (isRunning()) return;
String line = "";
stopped = false;
try {
while ((line = this.reader.readLine( )) != null && !stopped) {
if (line.toLowerCase( ).startsWith("ping")) {
LOGGER.log(Level.INFO,"> PING");
LOGGER.log(Level.INFO,"< PONG " + line.substring(5));
this.writer.write("PONG " + line.substring(5) + "\r\n");
this.writer.flush();
} else if (line.contains("PRIVMSG"))
{
String str[];
str = line.split("!");
final User msg_user = User.getUser(str[0].substring(1, str[0].length()));
str = line.split(" ");
Channel msg_channel;
msg_channel = Channel.getChannel(str[2], this);
String msg_msg = line.substring((str[0].length() + str[1].length() + str[2].length() + 4), line.length());
LOGGER.log(Level.INFO,"> " + msg_channel + " | " + msg_user + " >> " + msg_msg);
if (msg_msg.startsWith(commandTrigger))
onCommand(msg_user, msg_channel, msg_msg.substring(1));
if (msg_user.toString().equals("jtv") && msg_msg.contains("now hosting")) {
String hoster = msg_msg.split(" ")[0];
onHost(User.getUser(hoster), msg_channel);
}
onMessage(msg_user, msg_channel, msg_msg);
} else if (line.contains(" JOIN ")) {
String[] p = line.split(" ");
String[] pd = line.split("!");
if (p[1].equals("JOIN"))
userJoins(User.getUser(pd[0].substring(1)), Channel.getChannel(p[2], this));
} else if (line.contains(" PART ")) {
String[] p = line.split(" ");
String[] pd = line.split("!");
if (p[1].equals("PART"))
userParts(User.getUser(pd[0].substring(1)), Channel.getChannel(p[2], this));
} else if (line.contains(" WHISPER ")) {
String[] parts = line.split(":");
final User wsp_user = User.getUser(parts[1].split("!")[0]);
String message = parts[2];
onWhisper(wsp_user, message);
} else if (line.startsWith(":tmi.twitch.tv ROOMSTATE")) {
} else if (line.startsWith(":tmi.twitch.tv NOTICE"))
{
String[] parts = line.split(" ");
if (line.contains("This room is now in slow mode. You may send messages every"))
{
LOGGER.log(Level.INFO,"> Chat is now in slow mode. You can send messages every " + parts[15] + " sec(s)!");
} else if (line.contains("subscribers-only mode")) {
if (line.contains("This room is no longer"))
LOGGER.log(Level.INFO,"> The room is no longer Subscribers Only!");
else
LOGGER.log(Level.INFO,"> The room has been set to Subscribers Only!");
} else {
LOGGER.log(Level.INFO,line);
}
} else if (line.startsWith(":jtv MODE "))
{
String[] p = line.split(" ");
if (p[3].equals("+o")) {
LOGGER.log(Level.INFO,"> +o " + p[4]);
} else {
LOGGER.log(Level.INFO,"> -o " + p[4]);
}
} else if (line.toLowerCase().contains("disconnected"))
{
LOGGER.log(Level.INFO, line);
this.connect();
} else
{
LOGGER.log(Level.INFO,"> " + line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
This is code of method connect() in TwitchBot class.
public void connect(String ip, int port)
{
if (isRunning()) return;
try{
if (user == null || user == "")
{
LOGGER.log(Level.SEVERE, "Please select a valid Username");
System.exit(1);
return;
}
if (oauth_key == null || oauth_key == "")
{
LOGGER.log(Level.SEVERE,"Please select a valid Oauth_Key");
System.exit(2);
return;
}
#SuppressWarnings("resource")
Socket socket = new Socket(ip, port);
this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream(),StandardCharsets.UTF_8));
this.writer.write("PASS " + oauth_key + "\r\n");
this.writer.write("NICK " + user + "\r\n");
this.writer.write("USER " + this.getVersion() + " \r\n");
this.writer.write("CAP REQ :twitch.tv/commands \r\n");
this.writer.write("CAP REQ :twitch.tv/membership \r\n");
this.writer.flush();
String line = "";
while ((line = this.reader.readLine()) != null)
{
if (line.indexOf("004") >= 0) {
LOGGER.log(Level.INFO,"Connected >> " + user + " ~ irc.twitch.tv");
break;
}else {
LOGGER.log(Level.INFO,line);
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
Thank you for the help
This error means that the peer (i.e. the Twitch server) closes abruptly your connection. See this answer for more details.
I don't know if you can do something to fix that because it can have various external origins (peer crash...). Maybe you can wait and try to reconnect later (note that you might be blacklisted if you connect too often).

Writer dont writing in file but only create it

Im working on converter. I load file, start reading date from it and creating directories by year, month and day(+ another one dir) in witch ends are those converted text files. Everything is fine while creating those directories but in text files is nothing or only chunk of it.
public static void convertFile(File fileToConvert, File whereToSave, long shift) {
BufferedReader reader = null;
BufferedWriter writer = null;
String oldDate = "";
String newDate = "";
boolean boolDate = true;
try {
for (File file : fileToConvert.listFiles()) {
reader = new BufferedReader(new FileReader(file));
boolean block = true;
String line = "";
int lineCounter = 0;
while ((line = reader.readLine()) != null) {
if (lineCounter==0) {
block = true;
} else {
block = false;
}
line = line.replaceAll("[^0-9-,:+NaN.]", "");
String[] data = line.split(",");
if (block) {
data[0] = data[0].substring(0, 10) + " " + data[0].substring(10);
data[0] = SimulatorForRealData.timeShift(data[0], shift);
// ====================================================================================
newDate = data[0].substring(0, 4) + " " + data[0].substring(5, 7) + " "
+ data[0].substring(8, 10);
String savingIn = SimulatorForRealData.createDirs(whereToSave.toString(),
data[0].substring(0, 4), data[0].substring(5, 7), data[0].substring(8, 10));
File f = new File(savingIn + "\\" + FILE_NAME + ".log");
if (!newDate.equals(oldDate) && boolDate == false) {
writer.close();
boolDate = true;
} else {
oldDate = newDate;
boolDate = false;
}
writer = new BufferedWriter(new FileWriter(f));
// =====================================================================================
writer.write("<in date=\"" + data[0].substring(0, 10) + "T" + data[0].substring(11)
+ "\" t=\"1\" >\n");
writer.write(data[0] + "\n");
writer.write(0 + " " + 0 + " " + 0 + "\n");
for (int x = 0; x <= 10; x++) {
writer.write("NaN" + " ");
}
writer.write("\n");
for (String s : data) {
if (s.equals(data[0])) {
continue;
}
writer.write(s + ";");
}
writer.write("\n");
} else {
for (String s : data) {
writer.write(s + ";");
}
writer.write("\n");
}
lineCounter++;
if (lineCounter == 118) {
lineCounter = 0;
writer.write("</in>\n\n");
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is method where i perform it. Can someone help me. I tried different "writers" and nothing. I have suspicious that it will be problem in closing file but i dont know for sure.
I think you should close every writer you created, not only last one.
for (File file : fileToConvert.listFiles()) {
reader = new BufferedReader(new FileReader(file));
...
writer = new BufferedWriter(new FileWriter(f));
while ((line = reader.readLine()) != null) {
....
}
writer.close();
}
writer flushes all changes on disk only when buffer is overflowed or it is closed.
I see two main problems:
You create a file every time you read a line. You should put it outside the loop (or loops, if you want only one file)
Always data is written with the same filename. It should have different filenames if you make a file for every file read.

BufferedReader.readLine() pauses my application?

I am using this code:
while (true) {
sendData("hi");
System.out.println("Data sent!");
BufferedReader inFromServer;
try {
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e1) {
inFromServer = null;
e1.printStackTrace();
}
System.out.println("Recieved!"); //I see this de-bug message.
try {
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence); //I do NOT see this de-bug message!
} catch (IOException e) {
e.printStackTrace();
}
}
It successfully sends data to a server - And the server successfully sends data back:
public void run () {
//handle the session using the socket (example)
try {
sendData("Hi");
System.out.println("Data sent!"); //I see this de-bug message.
} catch (Exception e) {
e.printStackTrace();
}
}
However for some reason, the application seems to pause at the inFromServer.readLine() method. I see the "Recieved!" de-bug message, but not the "FROM SERVER" de-bug message.
There are no errors at all. It just seems to hang there.
Why is it hanging, and how can I fix that?
Well this simply means that inFromServer does not receive any line.
Make sure you really send a line,
Reads a line of text. A line is considered to be terminated by any one
of a line feed ('\n'), a carriage return ('\r'), or a carriage return
followed immediately by a linefeed.
Have a look at the readLine method :
String readLine(boolean ignoreLF) throws IOException {
StringBuffer s = null;
int startChar;
synchronized (lock) {
ensureOpen();
boolean omitLF = ignoreLF || skipLF;
bufferLoop:
for (;;) {
if (nextChar >= nChars)
fill();
if (nextChar >= nChars) { /* EOF */
if (s != null && s.length() > 0)
return s.toString();
else
return null;
}
boolean eol = false;
char c = 0;
int i;
/* Skip a leftover '\n', if necessary */
if (omitLF && (cb[nextChar] == '\n'))
nextChar++;
skipLF = false;
omitLF = false;
charLoop:
for (i = nextChar; i < nChars; i++) {
c = cb[i];
if ((c == '\n') || (c == '\r')) {
eol = true;
break charLoop;
}
}
startChar = nextChar;
nextChar = i;
if (eol) {
String str;
if (s == null) {
str = new String(cb, startChar, i - startChar);
} else {
s.append(cb, startChar, i - startChar);
str = s.toString();
}
nextChar++;
if (c == '\r') {
skipLF = true;
}
return str;
}
if (s == null)
s = new StringBuffer(defaultExpectedLineLength);
s.append(cb, startChar, i - startChar);
}
}
}
Note that this one receive a boolean, but calling readLine simply call this one with false passed, unless on Linux.
Notice the for(;;) loop, which is an infinite loop.
Try concatening to the "line" sent from the server
System.getProperty("line.separator");

BufferedReader is skipping every other line when reading my file in java

So Im working of reading a file containing appointments that I wrote to earlier in my code. I want to sift through the text file and find appointments on a certain date and add them to an ArrayList but when the BufferedReader goes through it, it skips ever other line... Heres my code
public ArrayList<String> read(int checkDay, int checkMonth, int checkYear) {
ArrayList<String> events = new ArrayList<String>();
BufferedReader in = null;
String read;
try {
in = new BufferedReader(new FileReader("calendar.txt"));
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] split = read.split(",");
System.out.println(read);
if (split[1].equals(Integer.toString(checkDay)) && split[2].equals(Integer.toString(checkMonth)) && split[3].equals(Integer.toString(checkYear))) {
events.add(split[0] + " : " + split[1] + "/" + split[2] + "/" + split[3]);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
return events;
}
You are reading the line twice..
while ((read = in.readLine()) != null) { // here
read = in.readLine(); // and here
You have error here:
while ((read = in.readLine()) != null)
read = in.readLine();
you should keep the read = in.readLine() in the while. and remove the other line.
pl try this
you r using "read = in.readLine())" two times in while loop that why it is skiping the lomes
public ArrayList<String> read(int checkDay, int checkMonth, int checkYear) {
ArrayList<String> events = new ArrayList<String>();
BufferedReader in = null;
String read;
try {
in = new BufferedReader(new FileReader("calendar.txt"));
while ((read = in.readLine()) != null) {
String[] split = read.split(",");
System.out.println(read);
if (split[0].equals(Integer.toString(checkDay)) && split[1].equals(Integer.toString(checkMonth)) && split[2].equals(Integer.toString(checkYear))) {
events.add(split[0] + " : " + split[1] + "/" + split[2] + "/" + split[3]);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
return events;

Why my program is going in the infinite loop?

I am trying to compile and execute C , C++ and Java codes taken as argument to a Java file and then check that the generated solution is correct or not as most of the website judge the solutions.Please anybody can tell me why my code is going in infinite loop and no out put is coming in file_name_output.txt. My other all files are correct as i have tested them by running the program on terminal.Here is my code :
import java.io.*;
import java.util.Scanner;
class test
{
public static void main(String args[])
{
String s=null,file_name,extension;
int pos = args[0].lastIndexOf(".");
extension = args[0].substring(pos+1);
file_name = args[0].substring(0,pos);
int lang = 0; // 1 -> c,c++ , 2 -> java
try
{
Process compile = null;
switch(extension)
{
case "c" : compile = Runtime.getRuntime().exec("gcc -g "+ args[0] + " -o "+file_name+" -lm");
lang = 1;
break;
case "cpp" : compile = Runtime.getRuntime().exec("g++ -g "+ args[0] + " -o "+file_name);
lang = 1;
break;
case "java" : compile = Runtime.getRuntime().exec("javac "+ args[0]);
lang = 2;
}
BufferedReader stdError = new BufferedReader(new InputStreamReader(compile.getErrorStream()));
if((s = stdError.readLine()) != null)
{
System.out.println("Compile Time Error OR Warning : ");
System.out.println(s);
while((s = stdError.readLine()) != null)
{
System.out.println(s);
}
}
double startTime, run_time;
Process run;
if(lang == 1)
{
startTime = System.nanoTime();
run = Runtime.getRuntime().exec("./"+file_name+" < "+file_name+"_input.txt > "+file_name+"_output.txt");
run_time = (System.nanoTime()-startTime)/(double)Math.pow(10,6);
}
else
{
startTime = System.nanoTime();
run = Runtime.getRuntime().exec("java "+file_name+" < "+file_name+"_input.txt > "+file_name+"_output.txt");
run_time = (System.nanoTime()-startTime)/(double)Math.pow(10,6);
}
System.out.println("RunTime : "+ run_time+" ms");
BufferedReader out_put = new BufferedReader(new FileReader(new File(file_name+"_output.txt")));
BufferedReader run_stdError = new BufferedReader(new InputStreamReader(run.getErrorStream()));
if(( s = run_stdError.readLine()) != null)
{
System.out.println("Runtime Error : ");
System.out.println(s);
while((s = run_stdError.readLine()) != null )
{
System.out.println(s);
}
}
else if((s = out_put.readLine()) != null)
{
String s_string = null;
int failed = 0;
File fs = new File(file_name+".txt");
BufferedReader br = new BufferedReader(new FileReader(fs));
if((!s.equals(s_string = br.readLine())))
{
failed = 1;
}
while(((s = out_put.readLine()) != null) & ((s_string = br.readLine()) != null) & (failed == 0))
{
if(!s.equals(s_string) )
{
failed = 1;
break;
}
}
if((failed == 1) || s != null || s_string != null)
{
System.out.println("Submmision Failed : ");
System.out.println("Either Output Is Wrong.\nOR\nYour Output Is Not According To The Given Format. ");
System.exit(0);
}
else
{
System.out.println("Submission Successful.");
}
}
}
catch(IOException e)
{
System.out.println("Some Error Has Occured : ");
e.printStackTrace();
System.exit(-1);
}
}
}
Diagnosis
Your program is not in an endless loop, it is blocking, and this is the line where it happens:
s = run_stdError.readLine()
unless there's something on the subprocess's stderr, this is going to block until the process dies. However, while waiting here you don't consume the process's stdout. It fills its output buffer and blocks.
The result: an interprocess deadlock.
Suggested fix
Use a ProcessBuilder and use its API to achieve redirection into files with no effort of your own. You have the redirectOutput(File) and redirectError(File) methods in there.

Categories

Resources