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
Related
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);
}
This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 5 years ago.
[Editing to explain this posted question is not a duplicate of the quoted question::
The structure, details and routines in the code in the quoted question is very different from mine. In addition, (s)he is sending multiple files and using arraylist in the core. While my code sends one file at a time and I never used arraylist in the core. So what is causing my occasional block may not overlap with the problems with his/her own code
In the first answer, EJP said "You are reading the socket until read() returns -1." I did not do this in my code
In the first answer, EJP said "You need to send the file size ahead of each file. You're already doing a similar thing with the file count. Then make sure you read exactly that many bytes for that file:" I already send exact file size ahead of the file sent in my original posted code so this is not a problem with my code and thus not the solution to the problem i face
The code in the second answer (in the quoted duplicate) serves a different purpose and thus I cannot extrapolate a solution from it to my own code.
The quoted question says "The subsequent files are created in the server folder, but they are 0 bytes" This is not a problem with my own code. When my code runs i receive full file bytes at both client and server ends.
Over all I have read through both the quoted question and the solutions provided and they do not provide any solutions to the problems I faced
thank you]
I am relatively new to client server coding.
I have Android as client and Java server. The system at the moment works like this::
Android client selects/loads a Jpeg image from sdcard, sends int size, string text and image file to server and server sends back integer and a text file with data back to client
My problem at the moment it works perfectly (randomly) only roughly ~60% of the runs. The remainder of the time it blocks permanently and I have to restart server to continue. [Certainly, a little over half of the time, the client-server system sends and receives without a glitch, but ~40% to 45% (permanent block) failure rate is unacceptable]
When it blocks there is no crash dump, stacktrace or error to read.
I have searched previous similar blocking questions and tried to close sockets and inputstream/outputstream and wrappers in different orders varying the permutations, but the success/permanent block rate remained the same
Because there is no stack trace and the randomness, I have no clue what causes the block. Except that using print statements all the server and client code the last prints that hang permanently is in the bytes receiving do-while loop in the server code
I am at a loss on what to do to solve this. I'm hoping experienced minds in this field would help solve this. Full code is below.
Java Server code
public class FileServer {
public static void main(String[] args) throws IOException {
int bytesRead;
int current = 0;
//===============================================
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
//==============================================
InetAddress IP=InetAddress.getLocalHost();
servsock = new ServerSocket(57925);
System.out.println("IP "+IP.getHostAddress()+" ***%% :"+servsock.getLocalPort());
while (true) {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
InputStream is = sock.getInputStream();
//=========================================================
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
//=================== read integer from client ============
String number = br.readLine();
System.out.println("integer received from client is "+String.valueOf(number));
byte [] mybytearray = new byte [Integer.valueOf(number)];
//=================== read filename string =====================================
String filename = br.readLine();
System.out.println("integer received from client is "+filename);
//===================== read file data stream bytes ================================
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
System.out.println("1 bytesRead "+bytesRead+" mybytearray.length "+mybytearray.length);
do {
bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
System.out.println("2 current "+current+" bytesRead "+bytesRead);
} while(current < Integer.valueOf(number));
//============================== initialise filename ======================
FileOutputStream fos = new FileOutputStream("C:\\Server root folder\\"+filename+".jpg");
BufferedOutputStream bos = new BufferedOutputStream(fos);
//========================== write bytes to server HDD =======================
bos.write(mybytearray, 0 , current);
System.out.println("4 current "+current);
bos.flush();
long end = System.currentTimeMillis();
// System.out.println("AT SERVER: bytesRead "+bytesRead+" current "+current);
// bos.close();
// ======================== write to-be-rendered data to text file ======================
File pathPlusfile = new File("C:/Server root folder/"+filename+".txt");
appendToFile( pathPlusfile, "file name:: "+filename+"* *", 20999 );
/**/ //================== Send Data in text file to Client ============================================
// send file
mybytearray = new byte [(int)pathPlusfile.length()];
fis = new FileInputStream(pathPlusfile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
//===============================================
os = sock.getOutputStream();
//=========================== send integer to client ===============
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
number = Integer.toString(mybytearray.length);
String sendMessage = number + "\n";
bw.write(sendMessage);
bw.flush();
//========================== send file to client ===================
System.out.println("Sending " + filename + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
//========================= close =================================
System.out.println("number "+number);
System.out.println("Done.");
bos.close();
bw.close();
osw.close();
os.close();
// fos.close();
// bis.close();
// fis.close();
// br.close();
isr.close();
is.close();
closeFile( );
// servsock.close();
// sock.close();
}
}
BufferedReader bufferedReader = null;
String stringObjectData = "";
public int numFromFile = 0;
static BufferedWriter bufferedWriter = null;
public static void appendToFile( File myPathPlusFile, String S, int num ){
try{
bufferedWriter = new BufferedWriter(new FileWriter(myPathPlusFile, true));
bufferedWriter.append( S );
bufferedWriter.append( " " );
bufferedWriter.append( Integer.toString(num) );
bufferedWriter.newLine();
bufferedWriter.flush();
}
catch (IOException e){
e.printStackTrace();
}
}
public static void closeFile( ){
try{
bufferedWriter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Android Client code
public class FSendfileActivity extends Activity {
private static final int SELECT_PICTURE = 1;
private Socket sock;
private String serverIP = "192.168.1.4";
private String selectedImagePath;
private ImageView img;
final static String qcd = "qcd";
String ImageDir2Client;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Button send;
//====================
public static String FILE_TO_RECEIVED=null;
String cFilename = null;
int bytesRead = -1;
int current = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fsendfile);
ImageDir2Client = Environment.getExternalStorageDirectory().getAbsolutePath();
cFilename = "fromServer000019ggg";
FILE_TO_RECEIVED = ImageDir2Client + "/client root/"+cFilename+".txt";
img = (ImageView) findViewById(R.id.ivPic);
((Button) findViewById(R.id.bBrowse)).setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult( Intent.createChooser( intent, "Select Picture" ), SELECT_PICTURE );
}
});
send = (Button) findViewById(R.id.bSend);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
new Thread(new Runnable() {
#Override
public void run() {
try {
sock = new Socket();
connection(sock, serverIP, 57925);
//=================== prepare buffer to read file ====================
File myFile = new File (selectedImagePath);
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
//=============== read file from sdcard to buffer ==========
bis.read(mybytearray,0,mybytearray.length);
//=================================================================
OutputStream os = sock.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//============================= send size integer ===================
String number = Integer.toString(mybytearray.length);
String sendMessage = number + "\n";
bw.write(sendMessage); // send size integer here
//============================= send file name =====================
String sendMessage2 = cFilename + "\n";
bw.write(sendMessage2); // send size filename here
osw.flush();
bw.flush();
//==================================================================
os.write(mybytearray,0,mybytearray.length); // send file
os.flush();
//================= client receiving data ==============================
InputStream is = sock.getInputStream();
//=================== read integer from client ==========
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
number = br.readLine();
//========================= set incoming file size=============================
mybytearray = new byte [Integer.valueOf(number)];
//========================read file bytes in chunks===============================
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(current < Integer.valueOf(number));
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bos.write(mybytearray, 0 , current);
bos.flush();
try{
bos.close();
osw.close();
os.close();
// fos.close();
// bw.close();
// br.close();
// isr.close();
bis.close();
sock.close();
// fis.close();
}
catch(Exception e){
e.printStackTrace();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try{
}
catch(Exception e){
e.printStackTrace();
}
}
}
}).start();
}
});
}
public static void connection(Socket s, String serverIP, int port) {
try {
Log.v(qcd, " before connecting ****...");
s.connect(new InetSocketAddress(serverIP, port), 120000);
Log.v(qcd, " socket connection DONE!! ");
} catch (UnknownHostException e) {
e.printStackTrace();
Log.v(qcd, " Unknown host..."+e);
} catch (IOException e) {
e.printStackTrace();
Log.v(qcd, " Failed to connect... "+e);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
img.setImageURI(null);
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
TextView path = (TextView) findViewById(R.id.tvPath);
path.setText("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
put the code after the accept into it's own thread and start it each time you get an accept.
edit: added threaded code example:
import java.io.*;
import java.net.*;
import java.util.concurrent.atomic.AtomicInteger;
public class So43462480 {
public interface Consumer<T> { // instead of 1.8 definition
void accept(T t);
}
class Server extends Thread {
Server(ServerSocket serverSocket,Consumer<Socket> consumer) {
super("Server");
this.serverSocket=serverSocket;
this.consumer=consumer;
}
#Override public void run() {
System.out.println("server running on: "+serverSocket);
while(true)
try {
Socket socket=serverSocket.accept();
if(consumer!=null)
consumer.accept(socket);
} catch(IOException e) {
System.out.println(getName()+" caught: "+e);
break;
}
}
final ServerSocket serverSocket;
final Consumer<Socket> consumer;
}
void read(Socket socket) {
InputStream inputStream=null;
try {
inputStream=socket.getInputStream();
BufferedReader in=new BufferedReader(new InputStreamReader(inputStream));
String string=in.readLine();
System.out.println(string+" from: "+socket);
socket.close();
System.out.println(Thread.currentThread().getName()+" succeeded");
} catch(IOException e) {
System.out.println(Thread.currentThread().getName()+" caught: "+e);
}
}
So43462480(String host,Integer service) throws IOException {
ServerSocket serverSocket=new ServerSocket();
SocketAddress socketAddress=new InetSocketAddress(host,service);
serverSocket.bind(socketAddress);
Consumer<Socket> socketConsumer=new Consumer<Socket>() {
#Override public void accept(Socket socket) {
final int n=accepts.incrementAndGet();
System.out.println("accepted #"+n+" from: "+socket);
new Thread(new Runnable() {
#Override public void run() {
read(socket);
}
},"accept #"+n).start();
}
};
new Server(serverSocket,socketConsumer).start();
}
static boolean send(String host,Integer service) {
Socket socket;
try {
socket=new Socket(host,service);
OutputStreamWriter out=new OutputStreamWriter(socket.getOutputStream());
out.write("hello\n");
out.flush();
socket.close();
return true;
} catch(IOException e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) throws InterruptedException {
final String host="localhost";
final Integer service=1237;
try {
So43462480 tcp=new So43462480(host,service);
} catch(Exception e) {
System.out.println("main caught: "+e);
}
for(int i=0;i<10;i++) {
boolean ok=send(host,service);
if(!ok)
System.out.println("send failed");
}
Thread.sleep(100);
for(Thread thread:Thread.getAllStackTraces().keySet())
System.out.println(thread);
}
AtomicInteger accepts=new AtomicInteger();
}
edit: a more simple solution:
import java.io.*;
import java.net.*;
import java.util.concurrent.atomic.AtomicInteger;
public class So43462480take2 {
class Server extends Thread {
Server(ServerSocket serverSocket) {
super("Server");
this.serverSocket=serverSocket;
}
#Override public void run() {
System.out.println("server running on: "+serverSocket);
while(true)
try {
Socket socket=serverSocket.accept();
final int n=accepts.incrementAndGet();
System.out.println("accepted #"+n+" from: "+socket);
new Thread(new Runnable() {
#Override public void run() {
InputStream inputStream=null;
try {
inputStream=socket.getInputStream();
BufferedReader in=new BufferedReader(new InputStreamReader(inputStream));
String string=in.readLine();
System.out.println(string+" from: "+socket);
socket.close();
System.out.println(Thread.currentThread().getName()+" succeeded");
} catch(IOException e) {
System.out.println(Thread.currentThread().getName()+" caught: "+e);
}
}
},"accept #"+n).start();
} catch(IOException e) {
System.out.println(getName()+" caught: "+e);
break;
}
}
final ServerSocket serverSocket;
}
So43462480take2(String host,Integer service) throws IOException {
serverSocket=new ServerSocket();
SocketAddress socketAddress=new InetSocketAddress(host,service);
serverSocket.bind(socketAddress);
new Server(serverSocket).start();
}
static boolean send(String host,Integer service) {
Socket socket;
try {
socket=new Socket(host,service);
OutputStreamWriter out=new OutputStreamWriter(socket.getOutputStream());
out.write("hello\n");
out.flush();
socket.close();
return true;
} catch(IOException e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) throws InterruptedException, IOException {
System.out.println("start");
final String host="localhost";
final Integer service=1237;
So43462480take2 tcp=new So43462480take2(host,service);
for(int i=0;i<10;i++) {
boolean ok=send(host,service);
if(!ok)
System.out.println("send failed");
}
Thread.sleep(1000);
try {
tcp.serverSocket.close();} catch(IOException e) {
System.out.println("close caught: "+e);
}
Thread.sleep(1000);
for(Thread thread:Thread.getAllStackTraces().keySet())
System.out.println(thread);
}
final ServerSocket serverSocket;
AtomicInteger accepts=new AtomicInteger();
}
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 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.
I am developing one program in which a user can download a number of files. Now first I am sending the list of files to the user. So from the list user selects one file at a time and provides path where to store that file. In turn it also gives the server the path of file where does it exist.
I am following this approach because I want to give stream like experience without file size limitation.
Here is my code..
1) This is server which gets started each time I start my application
public class FileServer extends Thread {
private ServerSocket socket = null;
public FileServer() {
try {
socket = new ServerSocket(Utils.tcp_port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
try {
System.out.println("request received");
new FileThread(socket.accept()).start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
2) This thread runs for each client separately and sends the requested file to the user 8kb data at a time.
public class FileThread extends Thread {
private Socket socket;
private String filePath;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public FileThread(Socket socket) {
this.socket = socket;
System.out.println("server thread" + this.socket.isConnected());
//this.filePath = filePath;
}
#Override
public void run() {
// TODO Auto-generated method stub
try
{
ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
try {
//************NOTE
filePath=(String) ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File f = new File(this.filePath);
byte[] buf = new byte[8192];
InputStream is = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(is);
ObjectOutputStream oos = new ObjectOutputStream(
socket.getOutputStream());
int c = 0;
while ((c = bis.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
// buf=new byte[8192];
}
oos.close();
//socket.shutdownOutput();
// client.shutdownOutput();
System.out.println("stop");
// client.shutdownOutput();
ois.close();
// Thread.sleep(500);
is.close();
bis.close();
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
NOTE: here filePath represents the path of the file where it exists on the server. The client who is connecting to the server provides this path. I am managing this through sockets and I am successfully receiving this path.
3) FileReceiverThread is responsible for receiving the data from the server and constructing file from this buffer data.
public class FileReceiveThread extends Thread {
private String fileStorePath;
private String sourceFile;
private Socket socket = null;
public FileReceiveThread(String ip, int port, String fileStorePath,
String sourceFile) {
this.fileStorePath = fileStorePath;
this.sourceFile = sourceFile;
try {
socket = new Socket(ip, port);
System.out.println("receive file thread " + socket.isConnected());
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public void run() {
try {
ObjectOutputStream oos = new ObjectOutputStream(
socket.getOutputStream());
oos.writeObject(sourceFile);
oos.flush();
// oos.close();
File f = new File(fileStorePath);
OutputStream os = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(os);
byte[] buf = new byte[8192];
int c = 0;
//************ NOTE
ObjectInputStream ois = new ObjectInputStream(
socket.getInputStream());
while ((c = ois.read(buf, 0, buf.length)) > 0) {
// ois.read(buf);
bos.write(buf, 0, c);
bos.flush();
// buf = new byte[8192];
}
ois.close();
oos.close();
//
os.close();
bos.close();
socket.close();
//Thread.sleep(500);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
NOTE : Now the problem that I am facing is at the first time when the file is requested the outcome of the program is same as my expectation. I am able to transmit any size of file at first time. Now when the second file is requested (e.g. I have sent file a,b,c,d to the user and user has received file a successfully and now he is requesting file b) the program faces deadlock at this situation. It is waiting for socket's input stream. I put breakpoint and tried to debug it but it is not going in FileThread's run method second time. I could not find out the mistake here. Basically I am making a LAN Messenger which works on LAN. I am using SWT as UI framework.
A more basic problem.
You are only processing the first socket.
while(true) {
new FileThread(socket.accept()).start();
}
As per the suggestion of Peter Lawrey i removed all the redundant streams code from my source code. Now the changed source code is as follows and the problem remains.
1) No change in FileServer. It is as it is .
2) FileThread
public class FileThread extends Thread {
private Socket socket;
private String filePath;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public FileThread(Socket socket) {
this.socket = socket;
System.out.println("server thread" + this.socket.isConnected());
// this.filePath = filePath;
}
#Override
public void run() {
// TODO Auto-generated method stub
try
{
OutputStream oos = socket.getOutputStream();
oos.flush();
InputStream ois = socket.getInputStream();
byte[] buf = new byte[8192];
ois.read(buf);
filePath = new String(buf);
System.out.println(filePath);
File f = new File(this.filePath);
InputStream is = new FileInputStream(f);
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
oos.close();
System.out.println("stop");
ois.close();
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
3) FileReceiverThread
public class FileReceiveThread extends Thread {
private String fileStorePath;
private String sourceFile;
private Socket socket = null;
public FileReceiveThread(String ip, int port, String fileStorePath,
String sourceFile) {
this.fileStorePath = fileStorePath;
this.sourceFile = sourceFile;
try {
socket = new Socket(ip, port);
System.out.println("receive file thread " + socket.isConnected());
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public void run() {
try {
OutputStream oos = socket.getOutputStream();
oos.write(sourceFile.getBytes());
oos.flush();
File f = new File(fileStorePath);
OutputStream os = new FileOutputStream(f);
byte[] buf = new byte[8192];
int c = 0;
// ************ NOTE
InputStream ois = socket.getInputStream();
while ((c = ois.read(buf, 0, buf.length)) > 0) {
os.write(buf, 0, c);
os.flush();
}
ois.close();
oos.close();
os.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
is there still something which i am missing ?