I have created a basic Client Server that will send image files in a specified directory over a network. The code worked last week but I came back to it today and it seems that I am only getting one file on the server side, even though the client prints out that it has sent all the image files in the directory.
It may be something in the client code but I think it is something on the server side.
Any help is greatly appreciated and if you have a more efficient solution, I am happy to change my code as necessary. My code is below:
ImageServer
package com.encima.network.server;
import java.io.*;
import java.net.*;
public class ImageServer{
ServerSocket ss;
Socket s;
ObjectOutputStream oos;
int port = 4440;
public ImageServer() throws IOException {
try {
ss = new ServerSocket(port);
System.out.println("Server started on Port: " + port);
} catch(IOException e) {
System.out.println("Serevr: Port-" + port + " not available, exiting.");
System.exit(0);
}
System.out.println("Server: Waiting for Client Connection...");
while(true) {
try {
s = ss.accept();
new ImageHandler(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
ImageServer is = new ImageServer();
}
}
ImageHandler
package com.encima.network.server;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import javax.imageio.ImageIO;
public class ImageHandler implements Runnable {
Socket s;
int count = 0;
public ImageHandler(Socket socket) {
s = socket;
Thread t = new Thread(this);
t.start();
}
#Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
FileOutputStream fos = new FileOutputStream("image" + System.nanoTime() + ".jpg");
count++;
//BufferedImage in = ImageIO.read(ois);
//ImageIO.write(in, "jpg", fos);
int ch = 0;
while(true) {
ch = ois.read();
if(ch == -1) {
break;
}
fos.write(ch);
}
fos.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Finally, the ImageClient
package com.encima.network.client;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javax.imageio.ImageIO;
import com.encima.network.ImageFilter;
public class ImageClient {
Socket s;
String ip = "localhost";
int port = 4440;
ObjectOutputStream oos;
public ImageClient(File[] files) throws IOException, ClassNotFoundException, InterruptedException {
try {
s = new Socket(ip, port);
System.out.println("Client connected to Server via " + ip + " on port 80");
} catch (Exception e) {
System.out.println("Client: Cannot find Host: " + ip + ". Exiting.");
System.exit(0);
}
oos = new ObjectOutputStream(s.getOutputStream());
for(File f: files) {
sendFile(f);
}
oos.close();
//System.out.println("Written Image " + i + " of " + files.length);
}
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
File dir = new File("/Users/christophergwilliams/Dropbox/PhD/Projects/PhD/Year 1/GSN/images");
File[] files = dir.listFiles(new ImageFilter());
ImageClient ic = new ImageClient(files);
}
public void sendFile(File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
//BufferedImage b = ImageIO.read(file);
//ImageIO.write(b, "jpg", oos);
int ch = 0;
while(true) {
ch = fis.read();
if(ch == -1) {
break;
}
oos.write(ch);
}
oos.flush();
System.out.println("Image Sent");
}
}
I am aware that it is a lot of code to read through but I do appreciate any help I can get on this!
I may be wrong but, for the sake of efficiency and network traffic, would it be beneficial to send the images as a zip from the client to the server?
Why are you using ObjectInputStream at all? You're not reading or writing any serialized objects - just raw binary data. Use whatever InputStream is provided, and read from that.
Anyway, that's not the big problem. The big problem is that you're just writing several files to one stream, with no indication of where one file is meant to finish and the next one is meant to start. How were you expecting to split the multiple files up? Options:
Use a delimiter between files (very ugly - you'd have to potentially escape any data which looked like the delimiter as you went along)
Prefix each file with its length
Send each file on a different connection
(You're also reading and writing a single byte at a time. Use the overloads of read/write which accept byte arrays.)
Related
I am writing a simple web server program for class that sends files to the web browser on request. I have written as much as I could. The difficulty is getting the data written to the OutputStream. I don't know what I am missing. I couldn't get the simple request to show up on the web browser.
I wrote it to the "name" OutputStream but when I reload the tab in the browser with the URL: "http://localhost:50505/path/file.txt" or any other like that "localhost:50505" it doesn't show up what I wrote to the OutputStream "name". It is supposed to show that.
package lab11;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;
import java.util.Scanner;
import java.io.OutputStream;
import java.io.PrintWriter;
public class main {
private static final int LISTENING_PORT = 50505;
public static void main(String[] args) {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(LISTENING_PORT);
}
catch (Exception e) {
System.out.println("Failed to create listening socket.");
return;
}
System.out.println("Listening on port " + LISTENING_PORT);
try {
while (true) {
Socket connection = serverSocket.accept();
System.out.println("\nConnection from "
+ connection.getRemoteSocketAddress());
handleConnection(connection);
}
}
catch (Exception e) {
System.out.println("Server socket shut down unexpectedly!");
System.out.println("Error: " + e);
System.out.println("Exiting.");
}
}
public static void handleConnection(Socket sok) {
try {
// Scanner in = new Scanner(sok.getInputStream());
InputStream one = sok.getInputStream();
InputStreamReader isr = new InputStreamReader(one);
BufferedReader br = new BufferedReader(isr);
String rootDirectory = "/files";
String pathToFile;
// File file = new File(rootDirectory + pathToFile);
StringBuilder request = new StringBuilder();
String line;
line = br.readLine();
while (!line.isEmpty()) {
request.append(line + "\r\n");
line = br.readLine();
}
// System.out.print(request);
String[] splitline = request.toString().split("\n");
String get = null;
String file = null;
for (String i : splitline) {
if (i.contains("GET")) {
get = i;
String[] splitget = get.split(" ");
file = splitget[1];
}
}
}
OutputStream name = sok.getOutputStream();
Boolean doesexist = thefile.exists();
if (doesexist.equals(true)) {
PrintWriter response = new PrintWriter(System.out);
response.write("HTTP/1.1 200 OK\r\n");
response.write("Connection: close\r\n");
response.write("Content-Length: " + thefile.length() + "\r\n");
response.flush();
response.close();
sendFile(thefile, name);
} else {
System.out.print(thefile.exists() + "\n" + thefile.isDirectory() + "\n" + thefile.canRead());
}
}
catch (Exception e) {
System.out.println("Error while communicating with client: " + e);
}
finally { // make SURE connection is closed before returning!
try {
sok.close();
}
catch (Exception e) {
}
System.out.println("Connection closed.");
}
}
private static void sendFile(File file, OutputStream socketOut) throws
IOException {
InputStream in = new BufferedInputStream(new FileInputStream(file));
OutputStream out = new BufferedOutputStream(socketOut);
while (true) {
int x = in.read(); // read one byte from file
if (x < 0)
break; // end of file reached
out.write(x); // write the byte to the socket
}
out.flush();
}
}
So, I don't know what I really did wrong.
When I load the browser with localhost:50505 it just says can't connect or localhost refused to connect.
You are writing the HTTP response in System.out. You should write it in name, after the headers, in the body of the response. You probably want to describe it with a Content-Type header to make the receiver correctly show the file.
I'm trying to transfer an mp3 file from Server to Client using Java NIO APIs.
In particular, I am trying to use transferTo & transferFrom methods.
I've already checked that the server recognizes the file appropriately and transfers to a FileChannel.
However, in the point of view of the client, it considers that the size of the FileChannel connected to the server is 0 which can be interpreted that the client did not receive any files from the channel.
Here are the results on the consoles of both server and client.
[Server]
Server is started...
java.nio.channels.SocketChannel[connected local=/127.0.0.1:7777 remote=/127.0.0.1:60430]Here comes a new client!
!!write activated!!
Channel size : 3622994
filename : C:\Users\InhoKim\Music\5 O'clock - Black Nut.mp3
java.nio.channels.SocketChannel[connected local=/127.0.0.1:7777 remote=/127.0.0.1:60430]The number of files transferred : 1
[Client]
!!read activated!!
Channel size : 0
How do I have to solve this problem?
Here are the full codes of both server and client
[Server]
import java.io.File;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.net.ServerSocket;
import java.net.InetSocketAddress;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.channels.FileChannel;
import java.io.FileInputStream;
import java.util.Set;
import java.nio.ByteBuffer;
public class MusicServer {
private Selector selector = null;
private ServerSocketChannel serverSocketChannel = null;
private ServerSocket serverSocket = null;
File dir = new File("C:\\Users\\InhoKim\\Music\\");
boolean test = true;
public static void main(String[] args) {
MusicServer ms = new MusicServer();
ms.initServer();
ms.startServer();
}
public void initServer() {
try {
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocket = serverSocketChannel.socket();
InetSocketAddress isa = new InetSocketAddress("localhost", 7777);
serverSocket.bind(isa);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch(Exception e) {e.printStackTrace();}
}
public void startServer() {
System.out.println("Server is started...");
try {
while (true) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
for (SelectionKey key : keys) {
SelectableChannel channel = key.channel();
if (channel instanceof ServerSocketChannel) {
if (key.isAcceptable())
accept(key);
} else {
if (key.isWritable()) {
if(test)
write(key);
}
}
}
}
} catch(Exception e) {e.printStackTrace();}
}
private void accept(SelectionKey key) {
ServerSocketChannel server = (ServerSocketChannel) key.channel();
try {
SocketChannel sc = server.accept();
if (sc == null) return;
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_WRITE);
System.out.println(sc.toString() + "Here comes a new client!");
} catch(Exception e) {e.printStackTrace();}
}
private void write(SelectionKey key) {
if(test)
System.out.println("!!write activated!!");
test = false;
SocketChannel sc = (SocketChannel) key.channel();
try {
File[] files = dir.listFiles();
int count = 0;
for (File file : files) {
count++;
FileInputStream fis = new FileInputStream(file);
FileChannel inChannel = fis.getChannel();
System.out.println("Channel size : " + (int)inChannel.size());
System.out.println("filename : " + file);
inChannel.transferTo(0, (int)inChannel.size(), sc);
fis.close();
break;
}
System.out.println(sc.toString() + "The number of files transferred : " + count);
} catch(Exception e) {e.printStackTrace();}
}
}
[Client]
import java.io.File;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.SelectionKey;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.util.Set;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
public class MusicClient {
private Selector selector = null;
private SocketChannel sc = null;
int count = 0;
public static void main(String[] args) {
MusicClient mc = new MusicClient();
mc.startServer();
}
public void initServer() {
try {
selector = Selector.open();
sc = SocketChannel.open(new InetSocketAddress("127.0.0.1", 7777));
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
} catch(Exception e) {e.printStackTrace();}
}
public void startServer() {
initServer();
startReader();
}
public void startReader() {
try {
while (true) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
for (SelectionKey key : keys) {
if (key.isReadable()) {
read(key);
System.exit(0);
}
}
}
} catch(Exception e) {e.printStackTrace();}
}
private void read(SelectionKey key) {
System.out.println("!!read activated!!");
SocketChannel sc = (SocketChannel) key.channel();
try {
File dir = new File("D:\\Target2\\");
FileOutputStream fos = new FileOutputStream(dir + "\\" + count + ".mp3"); // file name has been set as a number
count++;
FileChannel outChannel = fos.getChannel();
System.out.println("Channel size : " + (int)outChannel.size());
outChannel.transferFrom(sc, 0, (int)outChannel.size());
fos.close();
} catch(Exception e) {e.printStackTrace();}
}
}
in the point of view of the client, it considers that the size of the FileChannel connected to the server is 0
There is no such thing as a 'FileChannel connected to the server'. File channels are connected to files. What you have is a FileChannel connected to a new FileOutputStream which has just created a new file, whose size is therefore zero.
which can be interpreted that the client did not receive any files from the channel.
No, it can be interpreted as you telling the FileChannel to transfer zero bytes, which it did correctly.
You can't get the size of a SocketChannel, because it doesn't mean anything (consider a peer that just keeps sending and never closes the connection). So in this case you have to use Long.MAX_VALUE as the size. The transfer will complete when there are no more bytes to be transferred, or indeed before, especially as you are using non-blocking mode.
EDIT I don't see any reason to use non-blocking mode in the client. I would remove that, and the Selector. And transferFrom() must be called in a loop that terminates when it returns zero. Using transferTo() in the server is considerably more complex if you must use non-blocking mode there, as you have to register OP_WRITE when it returns zero and re-select and restart using an adjusted offset when you get it, and deregister OP_WRITE if it doesn't return zero.
I wrote a small client server program in Java. Server creates a ServerSocket on some port and keeps listening to it. Client sends some sample info to this server.
When I run Client the first time connection is accepted by server and info is printed by server. Then Client program exits. When I run Client again, connection is accepted however, data is not printed.
Please check following code.
Server Program
package javadaemon;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyDaemon {
public static void main(String [] args) throws IOException {
ServerSocket ss = new ServerSocket(9879);
ss.setSoTimeout(0);
while(true) {
Socket s = ss.accept();
System.out.println("socket is connected? "+s.isConnected());
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Input stream has "+dis.available()+" bytes available");
while(dis.available() > 0) {
System.out.println(dis.readByte());
}
}
}
}
Client Program
package javadaemon;
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String [] args) {
try {
System.out.println("Connecting to " + "127.0.0.1"
+ " on port " + 9879);
Socket client = new Socket("127.0.0.1", 9879);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
for(int i=0; i<100; i++ ) {
out.writeUTF("Syn "+i);
}
} catch(IOException e) {
}
}
}
Please help me in finding why next time no data is received by server.
The reason is before server side receive data, the Client already exits, I just debug it. (Can't explain whey it works at the first time.)
Just change your code like the below, and it works.
package javadaemon;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyDaemon {
public static void main(String [] args) throws IOException {
ServerSocket ss = new ServerSocket(9879);
ss.setSoTimeout(0);
while(true) {
Socket s = ss.accept();
System.out.println("socket is connected? "+s.isConnected());
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Input stream has "+dis.available()+" bytes available");
while(true) {
try {
System.out.println(dis.readByte());
} catch (Exception e) {
break;
}
}
}
}
}
The Client must add flush before exits,
package javadaemon;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String [] args) {
try {
System.out.println("Connecting to " + "127.0.0.1"
+ " on port " + 9879);
Socket client = new Socket("127.0.0.1", 9879);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
for(int i=0; i<100; i++ ) {
out.writeUTF("Syn "+i);
}
out.flush();
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
Place this in your Client program after for loop:
out.flush();
out.close();
client.close();
You need to flush your stream in order to push the data forward and clean the stream. Also, you will need to close your client socket.
I just tested this successfully.
I am trying to write an application using Java that will allow me to transfer files between a server and a client that requests the file. I plan to do it using sockets. My algorithm is somewhat like this:
On Server:
Create the connection between client and server.
Once connected find the file u need to send to client.
Then send the size of file to client.
Then send file broken down in parts.
On Client
After connection is created, ask for the file.
Receive the file size, then accept data till u reach file size.
Stop.
Please correct me if i am wrong somewhere in the algorithm
This isn't really an "algorithm" question; you're designing a (simple) protocol. What you've described sounds reasonable, but it's too vague to implement. You need to be more specific. For example, some things you need to decide:
How does the receiving program know what filename it should save to? Should that be sent through the socket, or should it just ask the user?
How is the file size transmitted?
Is it a character string? If so, how is its length indicated? (With a null terminator? A newline?)
Is it a binary value? If so, how big? (32 bits or 64?) What endianness?
What does "broken down in parts" mean? If you're writing to a TCP socket, you don't need to worry about packet boundaries; TCP takes care of that.
Does the recipient send anything back, like a success or failure indication?
What happens when the whole file has been transmitted?
Should both ends assume that the connection must be closed?
Or can you send multiple files through a single connection? If so, how does the sender indicate that another file will follow?
Also, you're using the terms "client" and "server" backward. Typically the "client" is the machine that initiates a connection to a server, and the "server" is the machine that waits for connections from clients.
You can also add Acknowledgement from server once a particular part of the file is recieved,
similar to what we have in HTTP protocol , that would ensure proper delivery of the file has been received on the server.
Here is the method that I use, it uses the socket's input and output streams to send and receive the files, and when it's done, it will automatically restart the server and reconnect to it from the client.
Server Code:
package app.server;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Functions
{
private static ServerSocket server;
private static Socket socket;
public static void startServer(int port)
{
try
{
server = new ServerSocket(port);
socket = server.accept();
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void restartServer()
{
new Thread()
{
#Override
public void run()
{
try
{
socket = server.accept();
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
}
}.start();
}
public static void sendFile(String inputFilePath)
{
FileInputStream fis;
BufferedInputStream bis;
OutputStream os;
BufferedOutputStream bos;
try
{
File input = new File(inputFilePath);
fis = new FileInputStream(input);
bis = new BufferedInputStream(fis);
os = socket.getOutputStream();
bos = new BufferedOutputStream(os);
byte[] buffer = new byte[1024];
int data;
while(true)
{
data = bis.read(buffer);
if(data != -1)
{
bos.write(buffer, 0, 1024);
}
else
{
bis.close();
bos.close();
break;
}
}
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
restartServer();
}
}
Client Code:
package app.client;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Functions
{
private static Socket socket;
private static String hostName;
private static int portNumber;
public static void connectToServer(String host, int port)
{
new Thread()
{
#Override
public void run()
{
try
{
hostName = host;
portNumber = port;
socket = new Socket(host, port);
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
}
}.start();
}
private static void reconnectToServer()
{
try
{
socket = new Socket(hostName, portNumber);
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void receiveFile(String outputFilePath)
{
InputStream is;
BufferedInputStream bis;
FileOutputStream fos;
BufferedOutputStream bos;
try
{
File output = new File(outputFilePath);
is = socket.getInputStream();
bis = new BufferedInputStream(is);
fos = new FileOutputStream(output);
bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int data;
while(true)
{
data = bis.read(buffer);
if(data != -1)
{
bos.write(buffer, 0, 1024);
}
else
{
bis.close();
bos.close();
break;
}
}
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
reconnectToServer();
}
}
This method works very well, I use it for my server and client file transfer program, all you need to do is enter the Server Host's IP address and choose a port number (I use 8888).
I have developed a screen in swings to download a file from the server. The whole concept works fine when i click the download button once. But when i click the download button second time, i find that the code pauses in getting the inputstream.(this i have followed it using the sysouts shown.)
Below shown are the two separate code snippets in two different files. TCPClient has the serversocket codings whereas the clientUI has the ui components which calls the TCPSever method to accept a socket and for requesting purpose.
In the tcp client side:
public TCPClient() throws Exception{
System.out.println("Inside TCPClient constructor---");
clientSocket = new Socket("localhost", 3500);
System.out.println("After creating socket instance---");
oos = new ObjectOutputStream(clientSocket.getOutputStream());
System.out.println("after getting the ouput stream---");
ois = new ObjectInputStream(clientSocket.getInputStream());
System.out.println("after getting the input stream.");
}
In the Client UI:
private void downloadButton_actionPerformed(ActionEvent e) throws Exception
{
Object selectedItem = contentsList.getSelectedValue();
System.out.println("selectedItem---"+selectedItem);
new TCPClient().downloadContents(nodeName,selectedItem.toString());
}
}
Kindly provide me a solution for this...
Below is the server code:
public void listening() throws Exception{
ServerSocket ss = new ServerSocket(3500);
System.out.println( "DataServer Is Listening..." );
while( true )
{
Socket soc = ss.accept();
ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream( soc.getOutputStream() );
String input = ( String ) ois.readObject( );
if(input.startsWith("downloadContents")){
String nodeName = ois.readObject().toString();
String contentName = ois.readObject().toString();
List contentsForNode = DBServer.getContentsForNode(nodeName);
for(Object obj : contentsForNode){
if(obj.toString().contains(contentName)){
new FileServer().send(obj.toString());
break;
}
}
}
}
}
public static void main( String[] args )
{
TCPServer obDataServer = new TCPServer();
try
{
obDataServer.listening();
}
catch ( Exception ioe )
{
ioe.printStackTrace();
}
}
At a guess, your server is single-threaded and is still reading its input stream, because you haven't closed the client socket. But it's anybody's guess until you post the relevant server code.
Do you take care of closing the socket after the file is downloaded (successfully/unsuccessfully)? It doesn't looks like it from the code snippet.
I'm not sure, but this might be the problem
This Is Server Class:
package client_to_server;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;`
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Server {
public static void main(String args[])throws IOException
{
ServerSocket serverSocket=new ServerSocket(2222);
System.out.println("New Server is Waiting");
Socket socket=serverSocket.accept();
System.out.println("My Connection Established");
DateFormat df=new SimpleDateFormat("HH:mm:ss");
Calendar c=Calendar.getInstance();
String starttime=df.format(c.getTime());
System.out.println("Start time is : "+starttime);
InputStream inputStream=socket.getInputStream();
byte[] readbyte=new byte[(1024*20)*1024];
FileOutputStream fileOutputStream=new FileOutputStream("/home/Manoj/copybulkfile5.zip");
int writebyte;
int count=0;
while((writebyte=inputStream.read(readbyte))!=-1)
{
if(writebyte>0)
count+=writebyte;
fileOutputStream.write(readbyte, 0, writebyte);
}
DateFormat df1=new SimpleDateFormat("HH:mm:ss");
Calendar c1=Calendar.getInstance();
String endtime=df1.format(c1.getTime());
System.out.println("END TIME is "+endtime);
System.out.println("THE WRITEBYTE VALUE IS "+writebyte+"THE READ BYTE VALUE IS"+count);
inputStream.close();
}
}
This Is Client Cass:
package client_to_server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String args[])throws IOException
{
//Socket socket=new Socket("localhost",2222);
Socket socket=new Socket("localhost",2222);
File file=new File("/home/Checking/Myfile.zip");
byte[] mybyte=new byte[(1024*20)*1024];
FileInputStream fileInputStream=new FileInputStream(file);
int count;
OutputStream outputStream=socket.getOutputStream();
while((count=fileInputStream.read(mybyte))!=-1)
{
outputStream.write(mybyte);
}
System.out.println("THIS FILE HAS BEEN SENT SUCCESSFULLY!!!");
//System.out.println("END TIME "+hr+"Hours"+min+"Minutes "+sec+"Seconds");
socket.close();
}
}