package experiments;
import java.io.*;
import java.net.Socket;
/** * * #author User */
/*THE CLIENT*/ public class UploadManager {
public static void setup(String address, int port,String path){
try( Socket s = new Socket(address,port); OutputStream out = s.getOutputStream(); InputStream in = s.getInputStream(); DataOutputStream dos = new DataOutputStream(out);
DataInputStream dis = new DataInputStream(in); )
{
/** * send file name and size to server */
System.out.println("processing file now");
File from = new File(path);
if(from.exists() && from.canRead()){
String FILENAME = from.getName();
long FILESIZE = from.length();
// String FILEHASH
/** * write all ,2 * to SERVER */ dos.writeLong(FILESIZE); dos.writeUTF(FILENAME);
//dos.writeUTF(FILEHASH);
dos.flush();
/** * what does SERVER HAS TO SAY? */
String RESPONSE_FROM_SERVER_1 =dis.readUTF();
if(RESPONSE_FROM_SERVER_1 . equalsIgnoreCase("SEND")){
uploadFresh(from,dos);
}
/** * in case there was an interruption we need * resume from an offset. */
if(RESPONSE_FROM_SERVER_1 . equalsIgnoreCase("RESUME")){
/** * length already sent */
System.out.println("resuming upload");
String LENGTH_ALREADY_READ =dis.readUTF();
long OFF_SET = Long.parseLong(LENGTH_ALREADY_READ);
/** * get the file name so we know the exact file */
String FILE_REAL_NAME = dis.readUTF();
resume(FILE_REAL_NAME,OFF_SET,dos);
}
}else{ System.out.println("Couldn't read: err");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
/** the resume method **/
private static void resume(String FILE_REAL_NAME,long OFF_SET,DataOutputStream to)throws Exception{
/** * copy from the stream or disk to server */
FileInputStream reader = null;
try{
reader = new FileInputStream(new File("c:\\movies\\hallow.mp4",FILE_REAL_NAME)); byte[] size = new byte [8192];
int COUNT_BYTES_READ ; reader.skip(OFF_SET);
//skip the length already written
while( (COUNT_BYTES_READ = reader.read(size)) >0{
to.write(size);
to.flush();
}
}finally{
if( reader != null ) reader.close();
to.close();
}
}
/** and the normal send method which works as expected **/
private static void uploadFresh(File from, DataOutputStream to)throws Exception{
/** * copy from the stream or disk to server */
FileInputStream reader = null;
try{
reader = new FileInputStream(from);
byte[] size = new byte [1024];
int COUNT_BYTES_READ ;
while( (COUNT_BYTES_READ = reader.read(size)) >0){
to.write(size,0,COUNT_BYTES_READ); to.flush();
}
}finally{
if( reader != null ) reader.close();
to.close();
}
}
}
//ThE SERVER
public class UserServer {
String ip_Adress;
int Port;
ServerSocket ss;
String path;
public UserServer(String ip_Adress,int Port ){
this.Port =Port; this.ip_Adress = ip_Adress; this. path = path;
}
public void startserver() throws IOException{
FileOutputStream fos =null;
// String realhash;
out.println("starting server");
this.ss= new ServerSocket(Port);
out.println("starting server on port"+Port); out.println("waiting for client conection......");
Socket visitor = this.ss.accept();
out.println("1 User connected to port");
/**
* reading file name and size from upload
*/
try( OutputStream ot =visitor.getOutputStream(); InputStream in = visitor.getInputStream(); DataOutputStream dos = new DataOutputStream(ot); DataInputStream dis = new DataInputStream(in); ){
System.out.println("processing debug");
long FILE_SIZE = dis.readLong();
System.out.println(FILE_SIZE+"processing");
String FILE_NAME = dis.readUTF(); System.out.println(FILE_NAME+"processing");
//String FILEHASH = dis.readUTF(); // System.out.println(FILEHASH+"processing");
File file = new File("c:\\aylo\\"+FILE_NAME);
/** * what do We Have TO Say? */
if(file.exists()){
long SIZE = file.length();
if(SIZE<FILE_SIZE){
String RESUME = "RESUME";
//tell client to resume the upload
dos.writeUTF(RESUME);
/*sending the resuming length in*/ string String size = String.valueOf(SIZE);
dos.writeUTF(size);
dos.flush();
fos=new FileOutputStream(file,true);
//append to exisiting file
byte[] b = new byte [1024]; int COUNT_BYTES_READ ;
while( (COUNT_BYTES_READ = dis.read(b)) >0){
fos.write(b);
fos.flush();
}
}
} else{
}
if(!file.exists()){
file.getParentFile().mkdirs();
file.createNewFile();
String SEND = "SEND";
dos.writeUTF(SEND);
dos.flush();
fos=new FileOutputStream(file);
byte b[]=new byte[1024];
int s;
while((s=dis.read(b))>0){
fos.write(b,0,s); fos.flush(); System.out.println(s+"processing");
}
}
System.out.println("i'm done reading ");
}catch(Exception ex){
ex.printStackTrace();
}finally{
fos.close();
if(this.ss!=null) this.ss.close();
}
}
//the main
public static void main(String []arg){
UserServer us = new UserServer("localhost", 2089);
us.startserver();
//start client
UploadManager.setup("localhost", 2089, ("c:\\movies\\hallow.mp4"));
}
}
I've searched and searched most forums and OS about this and found nothing.
What I'm trying to do is to learn or figure out how I can resume a file interrupted on upload through java socket.
Right now my code partially works, but there's always a break or gap which I assumed is caused by the new FileOutputStream(from,true); constructor
Can anyone pls check my methods and help point out my mistakes a sample code demo too will be nice. Thanks!
Please review java convention on variable names; it took me quite a while to find your problem, and a lot of it is down to the fact that your code looks unfamiliar. Also, really, review your names. Naming a byte buffer to transfer bytes 'size' is similar to naming your favourite cat 'horse'. It's going to cause confusion.
The problem: You have quite a few places where you do this:
byte[] buffer = new byte[8192];
int bytesRead = networkIn.read(buffer);
fileOut.write(buffer);
and this is incorrect. The 'write' call will write the entire buffer, all 8192 bytes, even if fewer than 8192 bytes were actually read. What you need to do is this:
byte[] buffer = new byte[8192];
int bytesRead = networkIn.read(buffer);
fileOut.write(buffer, 0, bytesRead);
NB: It is possible there are more bugs in your code; the above is one that's definitely going to cause issues and would explain why a resume operation produces a corrupted file.
Related
I have the following code for upload file from client to server tcp but when i try to open manually the file is empty why the good weight..
I have look lot of post on stackOverflow but nothing make change
Thx
(Sorry for my bad english)
Server:
public class ThreadServer extends Thread{
private Socket soc;
private FileOutputStream fos;
private BufferedOutputStream bos;
private InputStream in;
public ThreadServer (Socket soc) {
this.soc = soc;
}
public void run(){
try {
fos = new FileOutputStream("C:/Users/erwan/workspace/Word/server/text.txt");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
try {
in = soc.getInputStream();
int count = 0;
while((count= in.read(buffer, 0 , buffer.length)) != -1) {
System.out.println(count+" octets received...");
bos.write(buffer);
}
bos.flush();
bos.close();
in.close();
soc.close();
System.out.println("File sent succesfully!");
}catch(IOException e){
e.printStackTrace();
System.out.println("Une erreur est survenu");
}
}
}
client:
public class Client {
private static Socket as;
private static FileInputStream fis;
private static BufferedInputStream bis;
private static OutputStream out;
public static void main( String[] args ){
as = null;
try{
as = new Socket(InetAddress.getLocalHost(),4020);
File f = new File (args[0]);
byte [] buffer = new byte [(int) f.length()];
fis = new FileInputStream(f);
setBis(new BufferedInputStream(fis));
out = as.getOutputStream();
System.out.println("uploading...");
out.write(buffer,0,buffer.length);
out.flush();
out.close();
System.out.println("the file is uploaded.");
as.close();
}catch(IOException e){
e.printStackTrace();
}
}
The buffer in client does not seem to be populated with data. It is initialized as an array of bytes with the length of the file, but there are no read method calls done on the input stream. For the purpose of testing a fis.read(buffer) would probably quickly get some data into the buffer. Keep in mind that reads are not guaranteed to fill the whole length of the buffer. So especially if your file contains zeros then the lack of reading actual data into the buffer (of the client) is the likely culprit.
Other than that the server code also assumes that the read method fully populates the buffer, so the write method call should specify a length (count). So change bos.write(buffer) into bos.write(bos, 0, count). This will probably become apparent at the end of the file (if the file is more than 1024 bytes long), as the end of the file would become a repetition of some of the data from the previous chunk.
I've made a basic client server FTP program using sockets, but for some reason files are getting corrupted during the transfer. In the case below, I'm pushing a file to the server from the client. It almost works, since some files (such as a .png) transfer and open fine, but others (a .docx) don't. Any file that I transfer has a different MD5 to the one I sent.
Client code:
File file = null;
FTPDataBlock transferBlock;
int numBytesRead = 0;
int blockNumber = 1;
int blockSize = 1024;
byte[] block = new byte[blockSize];
fc = new JFileChooser();
// select file to upload
int returnVal = fc.showOpenDialog(Client.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
try {
// get total number of blocks and send to server
int totalNumBlocks = (int)Math.ceil((file.length()*1.0) / blockSize);
System.out.println("File length is: " + file.length());
FTPCommand c = new FTPCommand("PUSH", Integer.toString(totalNumBlocks));
oos = new ObjectOutputStream(sock.getOutputStream());
oos.writeObject(c);
oos.flush();
// send to server block by block
FileInputStream fin = new FileInputStream(file);
while ((numBytesRead = fin.read(block)) != -1){
transferBlock = new FTPDataBlock(file.getName(), blockNumber, block);
blockNumber++;
System.out.println("Sending block " + transferBlock.getBlockNumber() + " of " + totalNumBlocks);
oos = new ObjectOutputStream(sock.getOutputStream());
oos.writeObject(transferBlock);
oos.flush();
}
fin.close();
System.out.println("PUSH Complete");
// get response from server
ois = new ObjectInputStream(sock.getInputStream());
FTPResponse response = (FTPResponse)ois.readObject();
statusArea.setText(response.getResponse());
} catch (IOException | ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Server Code:
else if (cmd.getCommand().equals("PUSH")){
// get total number of file blocks
int totalNumBlocks = Integer.parseInt(cmd.getParameters());
// get first block
in = new ObjectInputStream(sock.getInputStream());
FTPDataBlock currentBlock = (FTPDataBlock)in.readObject();
// create file and write first block to file
File file = new File (workingDirectory + File.separator + currentBlock.getFilename());
FileOutputStream fOut = new FileOutputStream(file);
fOut.write(currentBlock.getData());
fOut.flush();
// get remaining blocks
while(currentBlock.getBlockNumber()+1 <= totalNumBlocks){
in = new ObjectInputStream(sock.getInputStream());
currentBlock = (FTPDataBlock)in.readObject();
fOut.write(currentBlock.getData());
fOut.flush();
}
fOut.close();
// send response
FTPResponse response = new FTPResponse("File Received OK");
out = new ObjectOutputStream(sock.getOutputStream());
out.writeObject(response);
}
FTPDataBlock class:
public class FTPDataBlock implements Serializable{
private static final long serialVersionUID = 1L;
private String filename;
private int blockNumber; // current block number
private byte[] data;
//constructors & accessors
}
I'm sure it's something small that I'm missing here. Any ideas?
This happened because the server was writing whole 1024 byte blocks to the file, even if there was less than 1024 bytes actually written to the block.
The solution (thanks to #kdgregory) was to use the return value of FileInputStream.read() to populate a new attribute in my FTPDataBlock class, int bytesWritten.
Then on the server side I could use:
FileOutputStream.write(currentBlock.getData(), 0, currentBlock.getBytesWritten());
to write the exact number of bytes to the file, instead of the whole block every time.
I think there may be a problem with the file extension. provide a option in the client side as:
FILE_TO_RECEIVED = JOptionPane.showInputDialog("Please enter the Drive followed by the file name to be saved. Eg: D:/xyz.jpg");
it is to help you to provide the correct file extension name.
then i think u should also provide the file size in client side like:
public final static int FILE_SIZE = 6022386;
and in then in the array block u used u can make the following changes as:
try {
sock = new Socket(SERVER, SOCKET_PORT);
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = sock.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
}
So this is a very simple question. I have been trying to research it, and yes I have slightly found some answers but i can't find out how it works so i have come to this.
I am making a simple game in java (pong) and their is a high score integer that i would like to be able save and load from a file (I have heard a lot about using a txt file so probably that, but i have also heard about using a xml i believe is what it is, but i did not look into that as much). How exactly do i program this?
Thank you to all who answer.
PS
I have looked into this code but I don't understand how it's workings
String strFilePath = "C://FileIO//WriteInt.txt";
try {
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
DataOutputStream dos = new DataOutputStream(fos);
int i = 100;
dos.writeInt(i);
dos.close();
} catch (IOException e) {
System.out.println("IOException : " + e);
}
The most simplest way is to create a file, i.e.
write the score to a file, e.g.
String user = "John";
int score = 100;
f = new BufferedWriter(new FileReader(filepath));
f.write(user + "=" + score); // assuming "=" is not inside the user name
f.close();
then read from the file when you need it, e.g.
f = new BufferedReader(new FileReader(filepath));
String line = f.readLine().trim();
String[] temp = line.split("="); // now temp is of the form ["John", "100"]
String user = temp[0];
int score = Integer.parseInt(temp[1]);
f.close();
I think you can solve this encoding the object into a file,but it wont be an xml, it will be a custom file that only your app will be able to open
public void save(Integer ... integersToEncode){
try{
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream (new File(/*yourFileName*/)));
for(Integer encoding : integersToEncode)
output.writeObject(encoding);
output.close();
}
catch(Exception e){
//What do you want to do if the program could not write the file
}
}
For reading
public Integer[] read(int size){
Integer[] objects = new Integer[size];
try{
ObjectInputStream input = new ObjectInputStream(new FileInputStream (new File(/*yourFileName*/)));
for(int i = 0; i < size ; i++)
objects[i] = (Integer)input.readObject();
input.close();
}
catch(Exception e){
//What do you want to do if the program could not write the file
}
return objects;
}
Maybe you were confused by the way the original code you posted was printing the char 'd' to the output file. This is the character's ASCII value, as you may know. The following modifications to your code make it work the way you were orginally looking at:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Game {
public static void main(String[] args) throws IOException {
Game game = new Game();
game.writeHighScore();
}
public void writeHighScore() throws IOException{
String strFilePath = "C:/Users/User/workspace/HighScore.txt";
FileInputStream is = null;
DataInputStream dis = null;
FileOutputStream fos = null;
DataOutputStream dos = null;
try
{
//create FileOutputStream object
fos = new FileOutputStream(strFilePath);
dos = new DataOutputStream(fos);
int i = 100;
dos.writeInt(i);
System.out.println("New High Score saved");
dos.close();
// create file input stream
is = new FileInputStream(strFilePath);
// create new data input stream
dis = new DataInputStream(is);
// available stream to be read
while(dis.available()>0)
{
// read four bytes from data input, return int
int k = dis.readInt();
// print int
System.out.print(k+" ");
}
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}finally{
// releases all system resources from the streams
if(is!=null)
is.close();
if(dis!=null)
dis.close();
if(fos!=null)
fos.close();
if(dos!=null)
dos.close();
}
}
}
For a homework i try to send a file and some parameter corresponding to this file.
So, i send my file and after my string.
The problem is my paramater go to my file and not in my variable. I understand the problem, my loop while continue to write in the file as long as he receives something, but i want to stop it and have my parameter outside from my file.
Here my code client:
public static void transfert(InputStream in, OutputStream out) throws IOException{
PrintWriter printOut;
byte buf[] = new byte[1024];
int n;
while((n=in.read(buf))!=-1)
out.write(buf,0,n);
printOut = new PrintWriter(out);
printOut.println("add");
System.out.println("envoie !!!");
printOut.println("1");
printOut.println("3");
// out.write(getBytes("add"),0,0);
printOut.flush();
}
and here my server code :
public static void transfert(InputStream in, OutputStream out, boolean closeOnExit) throws IOException
{
byte buf[] = new byte[1024];
int n;
while((n=in.read(buf))!=-1)
out.write(buf,0,n);
buffIn = new BufferedReader (new InputStreamReader(in));
String nom_methode = buffIn.readLine();
String param1 = buffIn.readLine();
String param2 = buffIn.readLine();
System.out.println("methode:"+nom_methode+"param1:"+param1+"param2:"+param2);
if (closeOnExit)
{
in.close();
out.close();
}
}
edit:
I still miss something, now i have an error with my thread, i think the problem is from my loop wich read my file in input.
Moreover, actually param still go in my file and not in my param... Why the loop dont stop after EOF ?
error:
Exception in thread "Thread-0" java.lang.IndexOutOfBoundsException
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:318)
at serveurthread.AcceptClient.transfert(AcceptClient.java:45)
at serveurthread.AcceptClient.run(AcceptClient.java:84)
at java.lang.Thread.run(Thread.java:722)
client:
public static void transfert(InputStream in, OutputStream out) throws IOException{
PrintWriter printOut;
printOut = new PrintWriter(out);
byte buf[] = new byte[1024];
int n;
while((n=in.read(buf))!=-1)
out.write(buf,0,n);
printOut.print('\u0004');
printOut.flush();
printOut.println("add");
System.out.println("envoie !!!");
printOut.println("1");
printOut.println("3");
// out.write(getBytes("add"),0,0);
printOut.flush();
}
server:
public static void transfert(InputStream in, OutputStream out, boolean closeOnExit) throws IOException
{
byte buf[] = new byte[1024];
int n;
while((n=in.read(buf))!= (int)'\u0004'){
out.write(buf,0,n);
}
buffIn = new BufferedReader (new InputStreamReader(in));
String nom_methode = buffIn.readLine();
String param1 = buffIn.readLine();
String param2 = buffIn.readLine();
System.out.println("methode:"+nom_methode+"param1:"+param1+"param2:"+param2);
if (closeOnExit)
{
in.close();
out.close();
}
}
You are going to need some kind of marker in your stream that signifies the end of the file. I suggest '\u0004' which is the EOF character. Basically, write this character after writing the file, then adjust the loop in the server like this:
while((n=in.read(buf))!=(int)'\u0004')
out.write(buf,0,n);
Now, the server stops reading the file when necessary, then can get around to reading the string.
Also, read returns a count of bytes read, not a char. I would pass one byte at a time through, by declaring bytes instead of byte arrays.
I am really thankful for everyone who would read this and try to help me, the following is the code I am trying to write for a server class for a socket-programming project for college:
import java.io.*;
import java.net.*;
import java.io.File;
class Server{
public static void main (String[]args)throws IOException{
ServerSocket socket1 = new ServerSocket (8000);
while (true) {
Socket incoming = socket1.accept();
new newclass(incoming).start();
}
}
}
class newclass extends Thread implements Runnable {
Socket incoming;
public newclass(Socket incoming) {
this.incoming = incoming;
}
public void run() {
try {
byte x = 0;
String z;
String s = "HTTP 1.0 200 Document follows";
String s1 = "Bad request message";
BufferedReader input = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
PrintWriter output = new PrintWriter(incoming.getOutputStream(), true);
DataOutputStream sending = new DataOutputStream(incoming.getOutputStream());
File directory = new File("C:\\Documents and Settings\\Ahmed\\Desktop\\bla\\Server");
File[] files = directory.listFiles();
int x1 = files.length;
if ((x1 - 3) < 10) {
boolean done = false;
while (!done) {
String line = input.readLine();
System.out.println(line);
if (line.equals("BYE")) {
output.println("BYE");
done = true;
} else {
if (line.trim().substring(0, 3).equals("GET ")) {
if (line.equals("<javalogo.png> HTTP 1.0")) {
File f = new File("javalogo.png");
int size = (int) f.length();
if (f.exists() == true) {
output.println(s);
output.println(size);
output.println("javalogo1.png");
DataInputStream bytefile = new DataInputStream(new BufferedInputStream(new FileInputStream(f)));
while (bytefile.available() != 0) {
x = bytefile.readByte();
sending.write(x);
}
} else {
System.out.println("Getting file from main server");
Socket socket2 = new Socket("127.0.0.1", 8100);
BufferedReader bUsr = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pOut = new PrintWriter(socket2.getOutputStream(), true);
BufferedReader bIn = new BufferedReader(new InputStreamReader(socket2.getInputStream()));
pOut.println("GET <javalogo.png> HTTP 1.0");
String rep = bIn.readLine();
if (rep.equals("HTTP 1.0 200 Document follows")) {
int len = Integer.parseInt(bIn.readLine());
String fname = bIn.readLine();
File f1 = new File(fname);
f1.createNewFile();
FileOutputStream fos = new FileOutputStream(f1);
DataInputStream dis = new DataInputStream(socket2.getInputStream());
for (int i = 0; i < len; i++) {
fos.write(dis.read());
}
fos.close();
} else if (rep.equals("File does not exist")) {
output.println("Sorry, but the file was neither found in the proxy server or the main server or the name is wrong.");
}
}
}
File f2 = new File("javalogo.png");
if (f2.exists() == true) {
int size = (int) f2.length();
output.println(s);
output.println(size);
output.println("javalogo.png");
DataInputStream bytefile = new DataInputStream(new BufferedInputStream(new FileInputStream(f2)));
while (bytefile.available() != 0) {
x = bytefile.readByte();
sending.write(x);
}
}
} else {
System.out.println(s1);
output.println(s1);
}
}
}
incoming.close();
}
output.println("Connecting to main server");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Now I don't understand why am I getting an error when I run the following client on it.
I get this really weird error where the buffered reader reads the first line from the user correctly but with the second one it gives me a null exception as if the client wrote null or something, I dont get it.
Here's the client code anyways, if anyone can help me I would be plenty thankful.
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws Exception {
Socket socket1 = new Socket("127.0.0.1", 8000);
BufferedReader bUsr = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pOut = new PrintWriter(socket1.getOutputStream(), true);
BufferedReader bIn = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
String cmd;
String rep;
while (true) {
cmd = bUsr.readLine();
pOut.println(cmd);
System.out.println(rep = bIn.readLine());
if (cmd.equals("BYE") || cmd.equals("END"))
break;
else if (rep.equals("HTTP 1.0 200 Document follows")) {
int len = Integer.parseInt(bIn.readLine());
String fname = bIn.readLine();
File f = new File(fname);
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
DataInputStream dis = new DataInputStream(socket1.getInputStream());
for (int i = 0; i < len; i++) {
fos.write(dis.read());
}
fos.close();
System.out.println("Success");
} else if (rep.equals("Connecting to main server")) {
Socket socket1 = new Socket("127.0.0.1", 8100);
BufferedReader bUsr = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pOut = new PrintWriter(socket1.getOutputStream(), true);
BufferedReader bIn = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
String cmd;
String rep;
while (true) {
cmd = bUsr.readLine();
pOut.println(cmd);
System.out.println(rep = bIn.readLine());
if (cmd.equals("BYE") || cmd.equals("END"))
break;
else if (rep.equals("HTTP 1.0 200 Document follows")) {
int len = Integer.parseInt(bIn.readLine());
String fname = bIn.readLine();
File f = new File(fname);
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
DataInputStream dis = new DataInputStream(socket1.getInputStream());
for (int i = 0; i < len; i++) {
fos.write(dis.read());
}
fos.close();
System.out.println("Success");
}
}
}
bIn.close();
pOut.close();
socket1.close();
}
}
This is the first time asking anything on this site, so if I did anything wrong I would be more than happy to change what I wrote.
By the way, the part in the server which states "getting file from main server" is a part where the server itself becomes a client for a main server, from where it gets the file and sends it to the client, I didn't add the main server code because it'd be too much code but basically it's the same as server without the if condition restricting it to 10 files in the directory only.
In general, when there is a NullPointerException either:
You have not instantiated your object
Your object has been destroyed (closed) and therefore does not exist
You have an invalid cast
Your code has overwritten your object pointer
You would need to examine your stack dump to see which of these is true.
From the Jav Docs the read can throw IOException if an I/O error occurs and IOException can give you the specified detail message. The error message string can later be retrieved by the Throwable.getMessage() method of class java.lang.Throwable.
Two points:
What does the IOException detail give you?
Since this is for your college course, try asking your classmates or TA for assistance
I'd be lying if I said I fully understand what your code is doing - But if you are getting null data when you are reading from a stream which you expect to contain data it could be that the output stream hasn't 'flushed' the data.
Make sure you call the flush() method on your Output streams after you have written to them
Ahemd, I see a number of potential errors and some actual bugs too in the classes as posted, but the code is too complicated for me to focus on the issue you are seeing. If you're still experiencing network bugs, try reducing the code and both client and server to the minimal possible to get communication going (send/read one line). If that doesn't work for you, post those classes and we'll be able to see the problems much more quickly than with the larger classes posted here.
Good luck.
If you are getting null from a BufferedReader.readLine() it means you have reached the end of input as it states in the javadoc for this method.
The best way to find your errors solution , is to see a trace. Without it I see more than one error in your code.
Regards.