Answer the question
In order to leave comments, you need to log in
How to properly implement a client-server application in Java?
I'm making a client-server application in Java. There are a couple of questions:
1) How to make a resume? For example, a piece of the file was transferred, but a piece was not, and the next time this piece was downloaded.
2) How to make it transmitted not by bytes, but by "pieces"? Because you can't transfer large files by bytes.
3) How to make it so that the files are read from the keyboard and transferred to the server? - This is very obvious, but after 7 hours without leaving the computer, the head does not boil. What needs to be done here? We count into a variable, and then? How to send and how to receive?
Customer:
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
public class Client {
public static void main(String[] argv) throws Exception {
Socket sock = new Socket("127.0.0.1", 4444);
byte[] mybytearray = new byte[1024];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("D:/client/file.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
bos.close();
sock.close();
}
}
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket servsock = new ServerSocket(4444);
File myFile = new File("D:/server/file.txt");
while (true) {
Socket sock = servsock.accept();
byte[] mybytearray = new byte[(int) myFile.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
sock.close();
}
}
}
Answer the question
In order to leave comments, you need to log in
Well, if the banal answers that immediately come to mind are
1 2 ) Break everything into pieces of N bytes in size (so that you can read it). When you start sending a file, you send how many pieces of what size it will be, and this can be used to resume downloading.
3) I do not really understand what the problem is. just pass
PS To understand client sockets in Java, first read the link
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question