First character missing from bufferedreader of socket - java

I am reading a string from a bufferedreader of a socket but the first character keeps going missing.
The only time I read from the stream is when I store it in the string dummy. So I don't understand why the first character would go missing.
I thought it might be something in the processMessage function which might be causing it, but I commented that line out and ran the code again and the first character still went missing.
Any help would be greatly appreciated.
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(serverTCP.getInputStream()));
while(true){
try{
//try and read the message and process it
String dummy = inFromServer.readLine();
System.out.println("received message1: " + dummy);
processMessage(dummy);
} catch (Exception e) {
}
}

Related

ObjectInputStream.readObject skips last line of text file

Fairly simple question, I have a server with some file, lets call it serverFile.txt and I wish to send it line by line to some client. to achieve this, i wrote this simple code on the server side
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while(line != null)
{
line = line + System.lineSeparator();
MMULogFileController.getOos().writeObject(line);
line = br.readLine();
System.out.println(line);
}
br.close();
where the MMULogFileController.getOos is the outputstream of the accepted socket.
It does indeed print all the lines of the file serverFile.txt
My problem is on the client side. This is the relevant code -
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
String line = (String)in.readObject();
File newLogFile = new File("newLog.txt");
PrintWriter ptofile = new PrintWriter(newLogFile.getName());
while(line != null)
{
ptofile.write(line);
try
{
line = (String) in.readObject();
}
catch(java.io.EOFException e)
{
line = null;
}
}
ptofile.close();
and it prints all the lines correctly into a new file on the client side, except for the very last line. I know it was sent from the server because it was printed, but on the client side it recieved null because it reaches EOF. Is there any way to deal with this?
Myself, I'd use a PrintStream to send the text out, and then read it in using either a BufferedReader or a Scanner. But having said that, if you insist on using an ObjectOutputStream, you should either flush or close it when done sending your file's text, and certainly close it when you're done using it.
Also, avoid this type of code:
catch(java.io.EOFException e)
{
line = null;
}
since this means that you're completely ignoring your exceptions. At least view the stack trace.

Java server/client application only displays messages upon pressing enter

Server Side:
try {
ServerSocket server_socket=new ServerSocket(port_number);
Socket client_socket= server_socket.accept();
PrintWriter output = new PrintWriter(client_socket.getOutputStream(),true);
BufferedReader input = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
BufferedReader stdIn=new BufferedReader(new InputStreamReader(System.in));
String userInput, clientOutput;
while ((userInput=stdIn.readLine())!="EXIT") {
if ((clientOutput=input.readLine())!=null) {
System.out.println("Client: "+clientOutput);
} if (userInput!=null) {
output.println(userInput);
output.flush();
}
}
}
Client Side:
try {
Socket client_socket= new Socket(hostname,port_number);
PrintWriter output = new PrintWriter(client_socket.getOutputStream(),true);
BufferedReader input = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
BufferedReader stdIn=new BufferedReader(new InputStreamReader(System.in));
String userInput,serverOutput;
while ((userInput=stdIn.readLine())!="EXIT") {
if ((serverOutput=input.readLine())!=null) {
System.out.println("Server: "+serverOutput);
} if (userInput!=null) {
output.println(userInput);
output.flush();
}
}
}
The code in my case makes sense to me, I cant seem to figure out why an enter still needs to be pressed, does it have something to do with .readLine()?
I checked out the following post Server Client in Java only displays message when I press enter, however the solution provided does not fix the situation.
Note: Initially there were no if statements in the while loop. The way I saw this to be an issue was that the while loop may get stuck on one of the lines, waiting for user/server input. Therefore implementing if statements allowed it to skip the waiting portion and re-run the loop.
Turns out I mixed my variables up.
The while loops should be:
while ((userInput=input.readLine())!="EXIT") {
It fixed it, but there are some other issues still present
does it have something to do with .getLine()?
Yes. If you look at the Javadoc for BufferedReader#readLine(), it clearly states that an end of line character terminates the String to be read:
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.

How to use BufferedReader correctly with sockets

The application is a basic chat client.
I got a Thread for getting data from the server.
I want to get every response from the server separately.
It prints in the console only when the loop breaks (when i send "exit" using the other parts of the application).
So when "System.out.println" responds it prints the whole buffer at once.
How can i make it work and print every response separately?
Thank you!
EDIT!!
The server respond should include "\n" after each line,
it works for me in this way.
Without "\n" it just waits until the loop breaks.
Is there a better way to do this without the "\n" issue?
class ServerThread implements Runnable {
#Override
public void run(){
BufferedReader in = null;
Socket socket;
try
{
if (Thread.currentThread().isAlive()) {
sendString("exit");
Thread.currentThread().interrupt();}
InetAddress serverAddress = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddress, SERVER_PORT);
outr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String serverResponse;
while((serverResponse = in.readLine()) != null)
{
System.out.println(serverResponse);
}
in.close();
outr.close();
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
You're using a BufferedReader and read it with in.readLine(), which, surprise surprise, will return the next line in the response. A line is a string terminated by a newline character, so your BufferedReader will have to wait until it sees a newline until it can return your line. If you don't want to use newlines in your response, don't use readLine(), use one of the other read() methods instead.

Reading from .txt file returns "No line Found"

I've made a GUI and a button.
My code looks like this:
private void jButtonSubmitActionPerformed(java.awt.event.ActionEvent evt) {
try {
Scanner scan = new Scanner(new File("persontest.txt"));
while(scan.hasNext()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException ex) {
System.out.println("File not found" + ex.getMessage());
} catch (Exception e) {
System.out.println("Some error" + e.getMessage());
}
persontest.txt contains the following text:
What do I contribute with when working in team work:
a. I come up with new ideas
b. I follow-up on things because I'm basically
thorough
c. I assess what is realistic and workable
d. I advocate alternative approaches objectively and unbiased
When trying to run I get "Some error No line found"
I tried removing all special characters from the text and I could read it, so I tried adding "UTF-8" to my scanner in this manner.
Scanner scan = new Scanner(new File("persontest.txt"), "UTF-8");
However this does not seem to do anything. I still get "No line found".
If this question has been asked before excuse me, I did a thorough search, but I either could not comprehend the question asked or the answer provided in context to my problem.
I changed my scanner to bufferedreader per Troubleshoot and Harshas example and it will now read the text even with special chars, however it won't display them correctly. I just get square boxes. It's a minor problem.
If persontest.txt is in classpath (i.e. inside jar or source folder) you can use:
YourClass.class.getClassloader().getResourceAsStream("persontest.txt")
First of all, make sure persontest.txt is in your main project folder, and not a sub-folder of that, as it will not find it otherwise.
I recommend using a BufferedReader to read it line by line. Here's how:
BufferedReader input = new BufferedReader(new FileReader("persontest.txt"));
String line;
while ((line = input.readLine()) != null && !line.isEmpty()) {
System.out.println(line);
}
It's good practice to check that the line isn't empty along with checking it isn't equal to null. For example, if a line was equal to \t it would be classed as empty, but not as null.
You could simply do this using
try {
String line;
BufferedReader br = new BufferedReader(new FileReader("persontest.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
if you need to do it with a Scanner you can try using
Scanner reader = new Scanner(new FileInputStream("persontest.txt");

reading string from socket error-connection reset error

java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(is));
String cmd=null;
while(is.available()<1){}
cmd = br.readLine();
System.out.println("cmd: "+cmd);
if(cmd.equals("search")){
String[] param = br.readLine().split(",");
for(String s:param){
System.out.println(s);
}
this the client code which accepts a string sent by server.but an exception is thrown in the line cmd=br.readLine()... a connection reset error..
server code is
Socket(InetAddress.getLocalHost(),1234);
OutputStream os = s.getOutputStream();InputStream is=s.getInputStream();
java.io.BufferedWriter bw=new java.io.BufferedWriter(new java.io.OutputStreamWriter(os));
String ss="search";
bw.println(ss);
bw.flush();
System.out.println("search cmded");
String param = "a,*,0,-1";
bw.println(param);
bw.flush();
System.out.println("param sent");
i've tried using print writer and the bufferedwriter but nothing is working correctly
so what could be the possible solution ???
also one thing worth mentioning is im using a listener service which creates a new server code mentioned above to handle particular client requests...
so wot could be soln now ??
In the server, your BufferedWriter is named bw but you're writing to pw.
Get rid of the available() test. You have it back to front, and it's not valid anyway. readLine() will block while there is no data. Just test the return value of readLine() for null, and break.

Categories

Resources