I have implemented a file transfer program using java socket. In this program, a file is sent from the client and its then downloaded in the Server. The program works almost correctly but the problem is the length of the received byte is always greater than the byte length sent from the client. for example, I sent 678888589 bytes from the client, but when I check the length of the received file at the server, I got 678925260 bytes. And for that reason, I am getting different checksum on the server side.
Here is my code:
Client Class:
public class Client
{
final static int ServerPort = 1234;
public static final int BUFFER_SIZE = 1024 * 50;
private static byte[] buffer;
public static void main(String args[]) throws UnknownHostException, IOException
{
Scanner scn = new Scanner(System.in);
buffer = new byte[BUFFER_SIZE];
for(int i=0;i<8;i++) {
Socket s1 = new Socket(ip, ServerPort);
DataOutputStream dos1 = new DataOutputStream(s1.getOutputStream());
SendMessage message = new SendMessage(s1, "test.mp4",dos1);
Thread t = new Thread(message);
System.out.println("Adding this client to active client list");
t.start();
}
}
}
class SendMessage implements Runnable{
String file_name;
Socket s;
public final int BUFFER_SIZE = 1024 * 50;
private byte[] buffer;
DataOutputStream dos;
public SendMessage(Socket sc,String file_name,DataOutputStream dos) {
this.file_name = file_name;
this.s=sc;
buffer = new byte[BUFFER_SIZE];
this.dos = dos;
}
#Override
public void run() {
File file = new File(file_name);
try {
sendFile(file, dos);
dos.close();
while(true) {
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
public void sendFile(File file, DataOutputStream dos) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE+1];
if(dos!=null&&file.exists()&&file.isFile())
{
FileInputStream input = new FileInputStream(file);
dos.writeLong(file.length());
System.out.println(file.getAbsolutePath());
int read = 0;
int totalLength = 0;
while ((read = input.read(buffer)) != -1) {
dos.write(buffer);
totalLength +=read;
System.out.println("length "+read);
}
input.close();
System.out.println("File successfully sent! "+totalLength);
}
}
}
Server Class
// Server class
public class Server
{
// Vector to store active clients
static Vector<ClientHandler> ar = new Vector<>();
// counter for clients
static int i = 0;
public static void main(String[] args) throws IOException
{
// server is listening on port 1234
ServerSocket ss = new ServerSocket(1234);
Socket s;
// running infinite loop for getting
// client request
while (true)
{
// Accept the incoming request
s = ss.accept();
System.out.println("New client request received : " + s);
// obtain input and output streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
System.out.println("Creating a new handler for this client...");
// Create a new handler object for handling this request.
ClientHandler mtch = new ClientHandler(s,"client " + i, dis, dos);
// Create a new Thread with this object.
Thread t = new Thread(mtch);
System.out.println("Adding this client to active client list");
// add this client to active clients list
ar.add(mtch);
// start the thread.
t.start();
// increment i for new client.
// i is used for naming only, and can be replaced
// by any naming scheme
i++;
}
}
}
// ClientHandler class
class ClientHandler implements Runnable
{
Scanner scn = new Scanner(System.in);
private String name;
final DataInputStream dis;
final DataOutputStream dos;
Socket s;
boolean isloggedin;
public static final int BUFFER_SIZE = 1024*50;
private byte[] buffer;
// constructor
public ClientHandler(Socket s, String name,
DataInputStream dis, DataOutputStream dos) {
this.dis = dis;
this.dos = dos;
this.name = name;
this.s = s;
this.isloggedin=true;
buffer = new byte[BUFFER_SIZE];
}
#Override
public void run() {
String received;
BufferedOutputStream out = null;
String outputFile = "out_"+this.name+".mp4";
BufferedInputStream in = null;
try {
in = new BufferedInputStream(s.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out = new BufferedOutputStream(new FileOutputStream(outputFile));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// while (true)
// {
try
{
long length = -1;
length = dis.readLong();
if(length!=-1)System.out.println("length "+length);
// String checkSum = dis.readUTF();
// System.out.println(checkSum);
int len=0;
long totalLength = 0;
// int len = 0;
while ((len = in.read(buffer,0,BUFFER_SIZE)) > 0) {
out.write(buffer, 0, len);
totalLength+=len;
// if(len<BUFFER_SIZE)break;
// System.out.println("length "+len);
if(len<=0)break;
}
File file = new File(outputFile);
System.out.println("total length1 "+totalLength+ " dif "+(totalLength-length));
System.out.println("output length "+file.length());
} catch (IOException e) {
e.printStackTrace();
}
}
private static String checksum(String filepath, MessageDigest md) throws IOException {
// file hashing with DigestInputStream
try (DigestInputStream dis = new DigestInputStream(new FileInputStream(filepath), md)) {
while (dis.read() != -1) ; //empty loop to clear the data
md = dis.getMessageDigest();
}
// bytes to hex
StringBuilder result = new StringBuilder();
for (byte b : md.digest()) {
result.append(String.format("%02x", b));
}
return result.toString();
}
}
It would be great if anyone can tell me what I am doing wrong. also, how can I verify the checksum on serverside. Another issue is the server side code get blocked in this block.
while ((len = in.read(buffer,0,BUFFER_SIZE)) > 0) {
out.write(buffer, 0, len);
System.out.println("length "+len);
if(len<=0)break;
}
It can't break the loop unless the client is disconnected. Although the file is recieved properly.
Regards.
You made a small mistake on the client code. You were writing out the full buffer instead of what is read from the file.
while ((read = input.read(buffer)) != -1) {
dos.write(buffer,0,read);
totalLength += read;
System.out.println("length " + read);
}
Related
I'm trying to transfer files over a socket in Java, my current approach for the server is:
Create new Thread
Thread sends file name using dos.writeUTF()
Thread sends file size using dos.writeLong()
Thread sends file using dos.write()
Where each Thread represents a client and dos is an instance of DataOutputStream.
Now, on the client I'm doing the same thing but reading instead of writing:
Read file name using dis.readUTF()
Read file size using dis.readLong()
Read file using dis.read()
Where dis is an instance of DataInputStream.
The problem is: when sending one file, everything goes right, but when I try to send 3 files, one after another, it looks like the server is writing everything correctly to the stream as expected but the client (After the first file, which means this starts happening from the second file) is stuck on dis.readUTF() and can't move on.
I've tried fixing this for days but can't get anything to work.
Here's the source code:
SERVER:
Main.java
public class Main {
public static void main(String[] args) {
boolean boolDebug = true;//TODO REMOVE THIS!!
ServerSocket serverSock = null;
List<Socket> clientSocks;
List<ClientThread> clientThreads;
try {
serverSock = new ServerSocket(9090);
} catch(Exception e){
e.printStackTrace();
}
clientSocks = new ArrayList<>();
clientThreads = new ArrayList<>();
ServerSocket finalServerSock = serverSock;
System.out.println();
System.out.println("Listening for incoming connections\n");
new Thread(){
#Override
public void run() {
super.run();
while (true) {
try {
Socket newSock = finalServerSock.accept();
clientSocks.add(newSock); //FIXME Remove sockets when closed
Thread thread = new ClientThread(newSock, usr, psw);
thread.start();
clientThreads.add((ClientThread)thread);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
}
ClientThread.java
public class ClientThread extends Thread {
private Socket socket;
private DataInputStream inStream;
private DataOutputStream outStream;
private String dbUser;
private String dbPassword;
public ClientThread(Socket socket, String DbUser, String DbPass) {
this.socket = socket;
this.dbUser = DbUser;
this.dbPassword = DbPass;
}
#Override
public void run() {
try {
inStream = new DataInputStream(socket.getInputStream());
outStream = new DataOutputStream(socket.getOutputStream());
sendFile("a.txt");
sendFile("b.txt");
sendFile("c.txt");
} catch (Exception e) {
e.printStackTrace();
}
}
void sendFile(String file){
try {
File f = new File(file);
outStream.writeUTF(file);
outStream.writeLong(f.length());
FileInputStream fis = new FileInputStream(f);
byte[] buffer = new byte[4096];
while (fis.read(buffer) > 0) {
outStream.write(buffer);
}
fis.close();
}catch(Exception e){
e.printStackTrace();
}
}
int getSize(byte[] buffer,long remaining){
try {
return Math.toIntExact(Math.min(((long) buffer.length), remaining));
}catch(ArithmeticException e){
return 4096;
}
}
}
CLIENT:
Main.java
class Main {
static int getSize(byte[] buffer, long remaining) {
try {
return Math.toIntExact(Math.min(((long) buffer.length), remaining));
} catch (ArithmeticException e) {
return 4096;
}
}
static void saveFile(Socket clientSock,DataInputStream dis) throws IOException {
String fileName = dis.readUTF();
File f = new File(fileName);
FileOutputStream fos = new FileOutputStream(f);
byte[] buffer = new byte[4096];
long filesize = dis.readLong();
int read = 0;
int totalRead = 0;
long remaining = filesize;
while ((read = dis.read(buffer, 0, getSize(buffer, remaining))) > 0) {
totalRead += read;
remaining -= read;
System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
}
fos.close();
}
public static void main(String[] args) throws Exception {
Socket sock = new Socket("192.168.2.17", 9090);
DataInputStream dis = new DataInputStream(sock.getInputStream());
saveFile(sock,dis);
saveFile(sock,dis);
saveFile(sock,dis);
}
}
Many thanks in advance, looking forward to fix this :(
Fixed by changing
while (fis.read(buffer) > 0) {
outStream.write(buffer);
}
to
int count;
while ((count = fis.read(buffer)) > 0) {
outStream.write(buffer, 0, count);
}
Inside ClientThread.java on the server side
I serialized an object to bytes and send to the server side.
in the server side i got the byte stream but i want to print the object/string i got from the server in order to verify i got it well
server side:
CarServerSocket = new ServerSocket(4441);
System.out.println("Server is ready and waiting for connection from client..\n");
try {
while (true) {
carSocket = CarServerSocket.accept();
System.out.println("Server Connected");
final DataInputStream bytesIR = new DataInputStream(carSocket.getInputStream());
bytesIRLength = bytesIR.readInt();
while (bytesIRLength > 0) {
byte[] messageIn = new byte[bytesIRLength];
bytesIR.readFully(messageIn,0,messageIn.length);
bytesIR.readUTF();
}
}
}catch(EOFException e ){
System.out.println("\ngot all objects from client.\ndisconnecting server...");
CarServerSocket.close();
carSocket.close();
}
}
Cliend side - serialization
objectOut.writeObject(CarList[i]); // converting object to bytes.
objectOut.flush();
objectInBytes = byteOut.toByteArray();
System.out.println("Sending car object #"+i);
dOut.writeInt(objectInBytes.length); // getting object bytes size.
dOut.write(objectInBytes); // sending object in bytes.
I tired to use: toString(), readUTF()... but no luck.
can anyone please advise how i solve it?
Thank you.
You can try to read data from your InputStream with some kind of InputStreamReader, something like this :
CarServerSocket = new ServerSocket(4441);
System.out.println("Server is ready and waiting for connection from client..\n");
try {
while (true) {
carSocket = CarServerSocket.accept();
System.out.println("Server Connected");
StringBuilder yourData = new StringBuilder();
new BufferedReader(new InputStreamReader(carSocket.getInputStream()))
.lines().forEach(stringBuilder::append);
System.out.println(yourData.toString());
}catch(EOFException e ){
System.out.println("\ngot all objects from client.\ndisconnecting server...");
CarServerSocket.close();
carSocket.close();
}
}
objectOut.writeObject(CarList[i]); // converting object to bytes.
objectOut.flush();
objectInBytes = byteOut.toByteArray();
System.out.println("Sending car object #"+i);
dOut.writeInt(objectInBytes.length); // getting object bytes size.
dOut.write(objectInBytes); // sending object in bytes.
All this is completely pointless. It just wastes time and space. Just use ObjectOutputStream.writeObject() directly to the socket at the sender, and ObjectInputStream.readObject() directly from the socket at the receiver.
You need to use ObjectInputStream to deserialize objects. Ok, so your object is entirely contained in a datagram that you've already received. You just need to turn the data buffer into an ObjectInputStream. Coding from the hip, this would be something like ...
try( ByteArrayInputStream bais = new ByteArrayInputStream(messageIn);
ObjectInputStream ois = new ObjectInputStream(bais)) {
Object o = ois.readObject();
}
Edit: Here is some complete code showing this working.
public class ByteStream {
public static void main(String[] args) throws IOException {
Server server = new Server(4441);
new Thread(server).start();
Client client = new Client(4441);
new Thread(client).start();
}
}
class Client implements Runnable {
private final Socket socket;
Client(int port) throws UnknownHostException, IOException {
socket = new Socket("localhost", port);
}
#Override
public void run() {
MyObject send = new MyObject();
send.x = 10;
send.msg = "X = ";
try {
try (DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(send);
oos.flush();
byte[] objectInBytes = baos.toByteArray();
int length = objectInBytes.length;
System.out.println("Client: sending 'objectInBytes' length = " + length);
dos.writeInt(length);
dos.write(objectInBytes);
} finally {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Server implements Runnable {
private final ServerSocket serverSocket;
Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
#Override
public void run() {
try {
try (Socket socket = serverSocket.accept();
DataInputStream bytesIR = new DataInputStream(socket.getInputStream())) {
int length = bytesIR.readInt();
byte[] messageIn = new byte[length];
bytesIR.readFully(messageIn);
System.out.println("Server: got datagram length = " + length);
process(messageIn);
} finally {
serverSocket.close();
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
private void process(byte[] messageIn) throws IOException, ClassNotFoundException {
try (ByteArrayInputStream bais = new ByteArrayInputStream(messageIn);
ObjectInputStream ois = new ObjectInputStream(bais)) {
Object o = ois.readObject();
System.out.println(o.getClass() + ": " + o);
}
}
}
class MyObject implements Serializable {
private static final long serialVersionUID = -1478875967217194114L;
double x;
String msg;
public String toString() { return msg + x; }
}
And the output:
Client: sending 'objectInBytes' length = 75
Server: got datagram length = 75
class MyObject: X = 10.0
I tried to create a multithread server socket. It can either send a string for available file or a file as a stream.
The problem is the else block, which sends requested file as a stream, works once. Where is the problem in my code and why it replies just once?
public class ServerThread extends Thread {
Socket socket = null;
public ServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
String message = null;
PrintStream ps = null;
String string = null;
File file = null;
BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ps = new PrintStream(socket.getOutputStream());
while ((message = bufferedreader.readLine()) != null) {
if (message.equals("list")) {
ps.println(Arrays.toString(getServerFiles()));
} else {
message = "FilesServer\\" + message;
file = new File(message);
//JOptionPane.showConfirmDialog(null, message);
if (file.exists()) {
BufferedInputStream bfInStream =
new BufferedInputStream(new FileInputStream(message));
BufferedOutputStream bufOutStream =
new BufferedOutputStream(socket.getOutputStream());
byte[] buffer = new byte[1024];
int read = 0;
while ((read = bfInStream.read(buffer)) != -1) {
bufOutStream.write(buffer, 0, read);
bufOutStream.flush();
}
bufOutStream.close();
System.out.println("File transfered");
}
}
}
} catch (Exception e) {
//JOptionPane.showConfirmDialog(null, e.getMessage());
}
}
private static String[] getServerFiles() {
String result[];
File folder = new File("FilesServer\\");
File[] listOfFiles = folder.listFiles();
result = new String[listOfFiles.length];
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
result[i] = listOfFiles[i].getName();
}
}
return result;
}
}
Above class is called from this class:
public class Server {
private int defaultPort = 8088;
public static void main(String[] args) throws IOException {
new Server().InitServer();
}
private void InitServer() throws IOException{
ServerSocket serversocket = new ServerSocket(8081);
while(true){
Socket socket = serversocket.accept();
new ServerThread(socket).start();
}
}
}
For server applications, you should use ServerSocket. ServerSocket must create new Socket each time new client requested a file (via accept() method). Then you send bytes into newly created socket and can safely close it.
Do not open and close the BufferedOutputStream bufOutStream. instead write directly to ps and close this after the while-loop.
closing bufOutStream closes the socket as MadProgrammer already mentioned.
I'm trying to send a jar file over a socket to a server.
Now everything seems to be working fine but on the other side of the socket, the jar is corrupted. The files have on both sides of the socket the same length. But when I try to use the file in bukkit, the file is corrupted.
The client code:
public class Main {
private Socket connection;
private ObjectOutputStream outStream;
private static String serverAddress = ""; // the ip address
static File fileLoc = new File("C:\\Users\\Tom\\Documents\\Qubeproject\\server\\plugins");
static String fileName = "\\WorldEdit.jar";
static File file ;
static InputStream IS;
static OutputStream OS;
static byte[] msgByte = new byte[1024];
public static void main(String[] arg0){
p("Starting this shit up");
file = new File(fileLoc + fileName) ;
try {
Socket connection = connection();
IS = connection.getInputStream();
OS = connection.getOutputStream();
OS.write(msg("LOL"));
//Authenciation
IS.read(msgByte);
if(new String(msgByte).trim().equals("OK")){
p("OK");
OS.write(msg(fileName));
//sending fileName
IS.read(msgByte);
p(new String(msgByte).trim());
//confirmation
OS.write(msg("l:" + (file.length())));
byte[] fileByte = new byte[(int)(file.length())];
FileInputStream jis = new FileInputStream(file);
int count = 0;
while((count = jis.read(fileByte))>0){
OS.write(fileByte,0,count);
OS.flush();
}
OS.flush();
setByteZero(msgByte);
IS.read(msgByte);
p(new String(msgByte).trim());
//confirmation
}else{
p("Authenciation failed");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void p (String s){
System.out.println(s);
}
private static byte[] msg(String s){
return s.getBytes();
}
private static Socket connection() throws IOException{
Socket socket = new Socket();
InetAddress ip = InetAddress.getByName(serverAddress);
InetSocketAddress address = new InetSocketAddress(ip,6969);
socket.connect(address,6969);
return socket;
}
private static byte[] setByteZero(byte[] workByte) {
for(int i=0;i < workByte.length;i++){
workByte[i] = 0;
}
return workByte;
}
the server code in bukkit
public class Checkup implements Runnable{
Server serverB;
ServerSocket server;
Socket client;
InputStream IS;
OutputStream OS;
static File destination;
byte[] msgByte = new byte[1024];
String filename;
long length;
Checkup (Server serverm){
serverB = serverm;
}
#Override
public void run() {
try{
server = new ServerSocket(6969);
}catch(Exception e){
}
try{
while(true){
client = server.accept();
IS = client.getInputStream();
OS = client.getOutputStream();
IS.read(msgByte);
if(msg(msgByte).equals("LOL")){
OS.write(msg("OK"));
IS.read(msgByte);
filename = msg(msgByte);
OS.write(msg("Q received name :" + filename));
OS.flush();
setByteZero(msgByte);
IS.read(msgByte);
length = Integer.parseInt(new String(msgByte).trim().replace("l:", ""));
OS.write(msg("Q received length :" + length));
byte[] fileByte = new byte[(int)length];
destination = new File("C:\\Users\\Quentin\\Desktop\\DE server\\plugins" + filename);
FileOutputStream fos = new FileOutputStream(destination);
int count = 0;
while((count =IS.read(fileByte))>0 ){
fos.write(fileByte);
fos.flush();
}
fos.flush();
fos.close();
OS.write(msg("Q received the jar!Bye"));
client.close();
}
}
}catch (Exception e){
e.printStackTrace();
try {
serverB.reload();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
finally{
}}
private String msg(byte[] strByte){
return new String(strByte).trim();
}
private static byte[] msg(String s){
return s.getBytes();
}
private static byte[] setByteZero(byte[] workByte) {
for(int i=0;i < workByte.length;i++){
workByte[i] = 0;
}
return workByte;
}
#Jon pointed you to the problem, here it is spelled out and formatted.....
The following code half-ignores the count (and the count is legal to be 0 too):
while((count =IS.read(fileByte))>0 ){
fos.write(fileByte);
fos.flush();
}
fos.flush();
fos.close();
and should be written as:
while((count =IS.read(fileByte))>=0 ){
fos.write(fileByte, 0, count);
}
fos.flush();
fos.close();
i write a program client-server with multi threading for send - receive file. The program runs and client send and server receive. the files are created but empty new files are created
Why? please help me
class client :
import java.io.*;
import java.net.Socket;
public class Client extends Thread {
Socket socket = null;
Socket socket1 = null;
public void sendFile() throws IOException {
String host = "127.0.0.1";
String host1 = "127.0.0.2";
socket = new Socket(host, 1024);
socket1 = new Socket(host1, 1025);
File file = new File("/home/reza/Desktop/link help");
File file1 = new File("/home/reza/Desktop/hi");
long length = file.length();
long length1 = file1.length();
final byte[] bytes = new byte[(int) length];
final byte[] bytes1 = new byte[(int) length1];
FileInputStream fis = new FileInputStream(file);
FileInputStream fis1 = new FileInputStream(file1);
#SuppressWarnings("resource")
final BufferedInputStream bis = new BufferedInputStream(fis);
final BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
#SuppressWarnings("resource")
final BufferedInputStream bis1 = new BufferedInputStream(fis1);
final BufferedOutputStream out1 = new BufferedOutputStream(socket1.getOutputStream());
Thread t = new Thread(new Runnable() {
public void run()
{
while(socket.isConnected())
{
Wait2();
try {
System.out.println("ok");
int count;
while ((count = bis.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
Thread t1 = new Thread(new Runnable() {
public void run() {
while(socket1.isConnected())
{
Wait2();
try {
System.out.println("ok1");
int count1;
while ((count1 = bis1.read(bytes1)) > 0) {
out1.write(bytes1, 0, count1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
t1.start();
t.start();
socket.close();
socket1.close();
}
public void Wait2()
{
try {
Thread.sleep(3000);
} catch (InterruptedException x) {
System.out.println("Interrupted!");
}
}
}
class server:
import java.io.*;
import java.net.*;
public class Server {
public Server()
{
Thread t = new Thread(new Client());
t.start();
Thread t1 = new Thread(new Client());
t1.start();
}
//#SuppressWarnings("null")
public void recivefile() throws IOException {
ServerSocket serverSocket = null;
ServerSocket serverSocket1 = null;
try {
serverSocket = new ServerSocket(1024);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number. ");
}
try {
serverSocket1 = new ServerSocket(1025);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number1. ");
}
Socket socket = null;
Socket socket1 = null;
InputStream is = null;
InputStream is1 = null;
FileOutputStream fos = null;
FileOutputStream fos1 = null;
BufferedOutputStream bos = null;
BufferedOutputStream bos1 = null;
int bufferSize = 0;
int bufferSize1 = 0;
try {
socket = serverSocket.accept();
socket1 = serverSocket1.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
is = socket.getInputStream();
is1 = socket1.getInputStream();
bufferSize = socket.getReceiveBufferSize();
bufferSize1 = socket1.getReceiveBufferSize();
//bufferSize2 = socket2.getReceiveBufferSize();
System.out.println("Buffer size: " + bufferSize);
System.out.println("file recieved");
System.out.println("Buffer size1: " + bufferSize1);
System.out.println("file recieved");
System.out.println("file recieved");
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
fos = new FileOutputStream("/home/reza/Desktop/reza");
bos = new BufferedOutputStream(fos);
fos1 = new FileOutputStream("/home/reza/Desktop/ali");
bos1 = new BufferedOutputStream(fos1);
} catch (FileNotFoundException ex) {
System.out.println("File not found. ");
}
byte[] bytes = new byte[bufferSize];
int count;
while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}
byte[] bytes1 = new byte[bufferSize1];
int count1;
while ((count1 = is1.read(bytes1)) > 0) {
bos1.write(bytes1, 0, count1);
}
bos.flush();
bos.close();
bos1.flush();
bos1.close();
is.close();
is1.close();
socket.close();
serverSocket.close();
socket1.close();
serverSocket1.close();
}
public static void main(String[] args) throws IOException
{
System.out.println("server is run, please send file");
Server s = new Server();
s.recivefile();
}
}
client test class:
import java.io.IOException;
public class clientTest extends Thread {
public static void main(String[] args) throws IOException, InterruptedException
{
Client client = new Client();
client.sendFile();
}
}
I believe this code in the server to be your issue:
while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}
byte[] bytes1 = new byte[bufferSize1];
int count1;
while ((count1 = is1.read(bytes1)) > 0) {
bos1.write(bytes1, 0, count1);
}
bos.flush();
bos.close();
bos1.flush();
bos1.close();
is.close();
is1.close();
socket.close();
serverSocket.close();
socket1.close();
serverSocket1.close();
So the server has connected to the client, then it immediately checks to see if there are any bytes to read, if not it stops reading and closes the connection. If this happens faster than the client can deliver any bytes, boom, no data is received. And it WILL happend faster than the client can send data because the client is connecting THEN starting thread to send the data.
Instead, the server should read on each connection for as long as the client has maintained the connection alive. The server needs to wait for the data to be received.
Notice that in your code, the client is waiting for the server to close the connection. But how is the server supposed to know when all the data is sent? Either the client must close the connection or the client must send an EOF-type marker to the server indicating an end of the data and that it is safe to close the connection.