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.
Related
I am implementing my own HTTP server using sockets. In my java project folder I have a folder /root where all the files are saved which can be downloaded (test.html, test.jpg), so when the user browses to let's say localhost:8080/test.html my server takes the file, reads it and sends the bytes to the client's browser ,setting the right headers. Everything works fine with the .html extension but I have a problem with the images...the browser says that the file cannot be shown properly.
Here is the class which I use to read the bytes from the file:
public class FileRequestHandler {
public FileRequestHandler(){
}
/*
* Method which reads a text-file and turns it into a string
*/
public String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
try {
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
return stringBuilder.toString();
} finally {
reader.close();
}
}
}
after executing readFile() I get a string(I will call it response).
Now I set the headers and send them to the client:
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: image/jpeg");
out.println("Content-Length: " + response.length());
out.println();
out.println(response);
out.flush();
out is a PrintWriter object.
As I already mentioned, this method works with a html-file and everything is shown. What am I doing wrong? Maybe the encoding of the raw-bytes is incorrect or the headers were set incorrectly?
Thank you for the help!
An image is not a text file. Yet you are apparently reading it as text using a BufferedReader. That will mangle it ... and the use of readLine() and the line reassembly mangles it some more.
Either way, the browser will be unable to decode the mangled image that your server is sending.
You should use InputStream / OutputStream subtypes rather than Reader / Writer subtypes, and you should NOT attempt to convert the image into a string at any point.
(It is also a bad idea to attempt to implement an HTTP server using socket-level I/O ... but that's a different issue.)
BufferedReader reader = new BufferedReader(new FileReader (file));
The problem starts here. Readers and Writers are for text. Images are not text. You should be using an input stream, and writing bytes directly to an output stream, not collecting them in a String.
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.
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) {
}
}
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.
I'm making application which needs to read strings from file on FTP Server. I use apache.commons.net.FTPClient for it. I have following code:
Log.e("sizzeee", String.valueOf(mClient.listFiles().length));
InputStream stream=mClient.retrieveFileStream(f.getName());
DataInputStream in=new DataInputStream(stream);
BufferedReader buf=new BufferedReader(new InputStreamReader(in));
List<String> tasks=new ArrayList<String>();
String s;
while ((s=buf.readLine())!=null) {
tasks.add(s.trim());
}
stream.close();
in.close();
buf.close();
Log.e("sizzeee", String.valueOf(mClient.listFiles().length));
That works correctly, but I have some problems: last Log instruction shows "0" files in current directory! But first Log instruction shows "6" files. Therefore I think that I don't close file stream or something else. Please, inform me about my mistake. Thank you