why doesn't the server receive the object sent from the client? - java

How do I handle the ObjectOutputStream and ObjectInputStream so that the Server instance correctly logs the received Object. Currently, it never gets that far. Each time the client runs, the server "waits for data", but never seems to actually receive it.
server:
package net.bounceme.dur.driver;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server {
private static final Logger log = Logger.getLogger(Server.class.getName());
private final RecordQueue recordsQueue = new RecordQueue();
public static void main(String[] args) {
Properties props = PropertiesReader.getProps();
int portNumber = Integer.parseInt(props.getProperty("port"));
while (true) {
try {
new Server().inOut(portNumber);
} catch (java.net.SocketException se) {
Logger.getLogger(Server.class.getName()).log(Level.FINE, "spammy", se);
} catch (IOException ioe) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ioe);
} catch (ClassNotFoundException cnf) {
Logger.getLogger(Server.class.getName()).log(Level.INFO, null, cnf);
}
}
}
public void inOut(int portNumber) throws IOException, ClassNotFoundException {
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket socket = serverSocket.accept();
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
log.info("...connected...waiting for data...");
MyRecord recordFromClient = (MyRecord) objectInputStream.readObject();
objectOutputStream.writeObject(recordFromClient);
objectOutputStream.flush();
objectInputStream.close();
objectOutputStream.close();
log.info(recordFromClient.toString());//never logs
System.out.println("never gets here");
}
}
Each time the client runs, the server waits for data, but, at least according to the output below, never receives it.
thufir#dur:~$
thufir#dur:~$ java -jar NetBeansProjects/Server/dist/Server.jar
Jun 29, 2014 9:28:45 PM net.bounceme.dur.driver.Server inOut
INFO: ...connected...waiting for data...
Jun 29, 2014 9:28:46 PM net.bounceme.dur.driver.Server inOut
INFO: ...connected...waiting for data...
client code:
package net.bounceme.dur.driver;
import java.net.*;
import java.io.*;
import java.util.Properties;
import java.util.logging.Logger;
public class Client {
private static final Logger log = Logger.getLogger(Client.class.getName());
public void put(String server, int portNumber, Socket socket, ObjectOutputStream objectOutputStream) throws IOException, ClassNotFoundException {
socket = new Socket(server, portNumber);
objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
MyRecord record = new MyRecord(1, "foo");
objectOutputStream.writeObject(record);
objectOutputStream.flush();
objectOutputStream.close();
}
public static void main(String args[]) throws IOException, ClassNotFoundException {
Properties props = PropertiesReader.getProps();
int portNumber = Integer.parseInt(props.getProperty("port"));
String server = (props.getProperty("server"));
Socket socket = null;
ObjectOutputStream objectOutputStream = null;
ObjectInputStream objectInputStream = null;
new Client().put(server, portNumber, socket, objectOutputStream);
}
}

Client and Server must agree with each other not only about how they send data but also when to close a socket. A unilateral close of a socket will close the connection and thwart the reception even of data that has already been sent. And I think that's what's happening here.
Client code:
objectOutputStream.writeObject(record);
objectOutputStream.flush();
objectOutputStream.close();
This is executed without interruption and so the socket is closed as soon as the last byte has been sent on the wire. Thus, the server's reply cannot be sent.
Server code:
MyRecord recordFromClient = (MyRecord) objectInputStream.readObject();
objectOutputStream.writeObject(recordFromClient);
Clearly, reception happens a little later than sending, and so the server blocks.
Keep the socket open from both sides until the client has received; then he may close the socket. The server should see an end-of-file when trying to read again, and can close accordingly. (More elaborate handshaking is possible, of course.)
Later
To corroberate, simply add a Thread.sleep(2000); between Client's flush and close - and the Server will indeed "get here".

Related

How to fix: java.net.SocketException: An established connection was aborted by the software in your host machine

Minimal Reproducible Example
Server.java
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.ServerSocket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(12345, 3);
Socket socket = serverSocket.accept(); // incoming request
new WorkerThread(socket).start();
}
}
class WorkerThread extends Thread {
private Socket socket;
public WorkerThread(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.flush();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); // line 28
// handle the request using oos and ois
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client.java
import java.net.Socket;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Client {
public static void main(String[] args) throws Exception {
try (Socket socket = new Socket("192.168.1.3", 12345)) {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.flush();
// ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); // line 11
// send some data only using oos
}
}
}
Thrown Exception
java.net.SocketException: An established connection was aborted by the software in your host machine
at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:325)
at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:350)
at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:803)
at java.base/java.net.Socket$SocketInputStream.read(Socket.java:966)
at java.base/java.io.ObjectInputStream$PeekInputStream.read(ObjectInputStream.java:2908)
at java.base/java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2924)
at java.base/java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:3421)
at java.base/java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:959)
at java.base/java.io.ObjectInputStream.<init>(ObjectInputStream.java:397)
at WorkerThread.run(Server.java:28)
The WorkerThread seems to be causing the issue, since the SocketException is not thrown if the code in the code of the WorkerThread#run method is placed in the Server#main method. See Note below.
The intent here is to have a separate Thread (other than the main Thread of the Server) handle each request as it comes, therefore the WorkerThread receives a reference to the Socket associated with the incoming connection.
The WorkerThread needs to open both oos and ois (even though they might not be both strictly needed for communication) because opening only the ois won't work. Further reading on why this happens.
What is the underlying cause of this issue? Is there a way to fix the problem other than the hacky (?) solution presented below?
Note
Running the above Client with this Server does not throw the Exception:
NonThreadedServer.java
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.ServerSocket;
public class NonThreadedServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(12345, 3);
Socket socket = serverSocket.accept(); // incoming request
try {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.flush();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
// handle the request using oos and ois
} catch (IOException e) {
e.printStackTrace();
}
}
}
Solution
Uncomment line 11 of Client, i.e. create an ObjectInputStream, even though it is not strictly needed for the communication:
Client.java
import java.net.Socket;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Client {
public static void main(String[] args) throws Exception {
try (Socket socket = new Socket("192.168.1.3", 12345)) {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.flush();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); // line 11
// send some data only using oos
}
}
}
As mentioned in the question, I don't know what the underlying issue is or whether this solution is the correct one. If it isn't, I'll make sure to mark another answer as the accepted one.

Java sockets application with two listeners hanging

I'm running a client and server on my local machine and trying to send text messages between the two. Both sides are able to read and write. I'm using ObjectInputStream and ObjectOutputStream because I need to serialize objects. Github repo
My issue is when I try to send messages from both sides, they don't get through to the other side and the listeners hang.
Host.java
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Host {
private ServerSocket serverSocket;
private Socket clientSocket;
private ObjectOutputStream out;
private ObjectInputStream in;
private int portNumber = Settings.PORT;
public Host() {
acceptConnection();
CommandListener commandListener = new CommandListener(in);
}
private void acceptConnection() {
try {
serverSocket = new ServerSocket(portNumber);
clientSocket = serverSocket.accept();
out = new ObjectOutputStream(clientSocket.getOutputStream());
in = new ObjectInputStream(clientSocket.getInputStream());
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
public ObjectOutputStream getOut() {
return out;
}
public ObjectInputStream getIn() {
return in;
}
}
Client.java
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
private int portNumber = Settings.PORT;
private ObjectOutputStream out;
private ObjectInputStream in;
private Socket clientSocket;
public Client(String ip) {
connectToHost(ip);
CommandListener commandListener = new CommandListener(in);
}
public ObjectOutputStream getOut() {
return out;
}
public ObjectInputStream getIn() {
return in;
}
private void connectToHost(String ip) {
try {
clientSocket = new Socket(ip, portNumber);
out = new ObjectOutputStream(clientSocket.getOutputStream());
in = new ObjectInputStream(clientSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + ip);
e.printStackTrace();
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " + ip);
e.printStackTrace();
}
}
}
The CommandListener.java class is a thread which is started independently by both the client and the server.
import java.io.IOException;
import java.io.ObjectInputStream;
public class CommandListener implements Runnable{
private ObjectInputStream in;
public CommandListener(ObjectInputStream in) {
this.in = in;
run();
}
public void run() {
String inboundCmd;
try {
System.out.println("listener running, waiting for inbound command");
inboundCmd = (String) in.readObject();
System.out.println("listener read inbound command" + inboundCmd);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Both hang after printing out listener running, waiting for inbound command.
Here's how I start the client and the server:
RunHost.java
import java.io.IOException;
import java.io.ObjectOutputStream;
public class RunHost {
public static void main(String[] args) throws IOException {
Host host = new Host();
ObjectOutputStream out = host.getOut();
out.writeObject("host sending");
out.flush();
}
}
RunClient.java
import java.io.IOException;
import java.io.ObjectOutputStream;
public class RunClient {
public static void main(String[] args) throws IOException {
Client client = new Client("localhost");
ObjectOutputStream out = client.getOut();
out.writeObject("client sending");
out.flush();
}
}
Any idea how to fix this?
The reason why it seems like both the host and the client are "hanging" is simply because nobody managed to write anything before listening to the other party.
You should be running RunHost.java before RunClient.java. Starting from there, you can trace the program:
Construct a new Host (i.e. RunHost.java is ran)
Blocks and wait for a client socket to connect
Construct a new Client (i.e. RunClient.java is ran)
Both ServerSocket's and ClientSocket's input and output streams are initialised
Both ServerSocket and ClientSocket start constructing CommandListener
Both ServerSocket and ClientSocket start listening for an input
See the problem yet? The main issue is because you call the method run() within the CommandListener constructor, so both Server and Client side start to block on listening without anyone having sent anything.
A quick fix would be to take out the run() call from the CommandListener constructor function, and then call it separately when you are ready for it.
For example:
Change the constructor in CommandListener.java to:
public CommandListener(ObjectInputStream in) {
this.in = in;
}
Add a way to get the CommandListener for the client in Client.java (note that this means you should store the CommandListener by doing cl = new CommandListener(in); in the Client constructor):
public CommandListener getCL() {
return cl;
}
Change RunClient.java to something like:
public static void main(String[] args) throws IOException {
Client client = new Client("localhost");
ObjectOutputStream out = client.getOut();
out.writeObject("client sending");
out.flush();
CommandListener cl = client.getCL();
cl.run();
}
And lastly, call CommandListener's run() method in Host's constructor:
public Host() {
acceptConnection();
CommandListener commandListener = new CommandListener(in);
commandListener.run();
}
And it should work as per expected.
But to be honest, given the mess that CommandListener is causing, you may want to reconsider having that class in the first place. I mean, over here it doesn't seem to be necessary, so...
P/S Feel free to let me know if anything is unclear/ it still does not work

Java – Server Only Responds when the Client has Stopped

I recently programmed a simple Java server, and a client to test the server. The server is supposed to receive messages from the client, and send a random substring of the message back. The problem is this: When I send the message using the client program, the server does not respond. Then, when I kill the client program, the server leaps into action, and attempts to send the data back to the client. The server reads the data correctly but starts processing it only when I stop the client program.
This is the client code:
import java.io.*;
import java.net.*;
class ServerTest{
public static void main(String args[]) throws Exception{
Socket clientSocket = new Socket(myIpAdress, 8001);
//Send the message to the server
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String sendMessage = "randSubstring:StackOverflowIsAwsome";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent: "+sendMessage);
String message = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())).readLine();
System.out.println("Message received from the server : " +message);
clientSocket.close();
}
}
My server code consists of two classes. This one is the listener:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerListener {
public static void main(String args[]) throws Exception {
String clientSentence;
ServerSocket socket = new ServerSocket(8001);
while(true) {
Socket connectionSocket = socket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
//DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = input.readLine();
if(clientSentence.startsWith("randSubstring:")){
Thread connection = new Thread(new ServerConnection(connectionSocket, clientSentence));
connection.start();
}
Thread.sleep(300);
}
}
}
This is the thread that will not start until the client is stopped:
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Random;
public class ServerConnection implements Runnable{
private Socket serverConnection;
private String sentence;
public ServerConnection(Socket connection, String clientSentence){
serverConnection = connection;
sentence = clientSentence;
}
#Override
public void run() {
Random r = new Random();
String substring = sentence.substring(0, r.nextInt(sentence.length()));
try {
OutputStream os = serverConnection.getOutputStream();
OutputStream out = new BufferedOutputStream(os);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
bw.write(substring);
bw.close();
out.close();
os.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am using a Macintosh with Yosemite. Is this happening because I am trying to run the programs on the same computer, or would the problem occur if the programs were run from different computers? Any help is appreciated.
In the server you do a readLine(..), which means that it will wait for a end-of-line character.
But in your sender code, you just send a string with no line ending.
So either you make sure you also send a end of line char or your server wait's for something else as "delimiter"
You're reading a line but you aren't writing a line. Add a line terminator to the sent message. Otherwise readLine() won't return until the peer closes the connection.
NB The I/O in the try block after the accept should be in the Runnable, not where it is. Don't do I/O in the accept loop.

Client Server File Transfer Java

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).

not able to get inputstream in server socket file transfer

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();
}
}

Categories

Resources