Connection reset by peer: socket write error (Socket Programing) - java

I am trying to implement a Server Client application using Socket. The client request to the server for a specified file, the server will accept the client request and send the file which client requested. But while i am running my code i got the error "Connection reset by peer: socket write error" at the server side. Why this happening ? My code is below
Server.java
package Client_Server;
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server extends Thread {
static Server s;
static ServerSocket ss;
static Socket clientSocket;
public static void main(String[] args) throws IOException {
s = new Server();
ss = new ServerSocket(1122);
while(true) {
System.out.println("waiting for a connection....");
clientSocket = ss.accept();
Thread thread = new Thread(s);
thread.start();
}
}
public void run() {
try {
server();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void server() throws IOException {
System.out.println("accepted connection :"+clientSocket);
BufferedReader bfr = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String fileName = bfr.readLine();
System.out.println("server side got the file name : "+fileName);
File myFile = new File(fileName);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
OutputStream os = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(clientSocket.getOutputStream()));
byte[] buffer = new byte[clientSocket.getSendBufferSize()];
long expect = myFile.length();
long left = expect;
int inlen = 0;
while (left > 0 && (inlen = bis.read(buffer, 0, (int)Math.min(left, buffer.length))) >= 0) {
dos.write(buffer, 0, inlen);
left -= inlen;
}
dos.flush();
if (left > 0) {
throw new IllegalStateException("We expected " + expect + " bytes but came up short by " + left);
}
if (bis.read() >= 0) {
throw new IllegalStateException("We expected only " + expect + " bytes, but additional data has been added to the file");
}
}
}
Client2.java
package Client_Server;
import static Client_Server.MainServer.sock;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class Client2 {
public static void main(String[] args) throws IOException {
File outdir = new File("copiedfiles");
if (!outdir.isDirectory()) {
outdir.mkdirs();
}
String fileName = "som.jpg";
Socket sock = new Socket("localhost", 1122);
System.out.println("connecting.....");
OutputStream os = sock.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
pw.println(fileName);
DataInputStream clientData = new DataInputStream(new BufferedInputStream(sock.getInputStream()));
OutputStream output = new BufferedOutputStream(new FileOutputStream(new File(outdir, "received_from_client_" + fileName)));
long size = clientData.readLong();
long bytesRemaining = size;
byte[] buffer = new byte[sock.getReceiveBufferSize()];
int bytesRead = 0;
while (bytesRemaining > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, bytesRemaining))) >= 0) {
output.write(buffer, 0, bytesRead);
bytesRemaining -= bytesRead;
}
output.flush();
if (bytesRemaining > 0) {
throw new IllegalStateException("Unable to read entire file, missing " + bytesRemaining + " bytes");
}
if (clientData.read() >= 0) {
throw new IllegalStateException("Unexpected bytes still on the input from the client");
}
}
}
Please help me to solve this.
The Exception is
Exception in thread "main" java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:122)
at java.io.DataOutputStream.write(DataOutputStream.java:107)
at Client_Server.Server.server(Server.java:54)
at Client_Server.Server.main(Server.java:27)
Java Result: 1

Related

How to check if the file is used by another thread Java with Socket?

I want to implement an application that will allow me to transfer files between client and server.
The client requests a file, if the file is not used by another client the server will send the file, otherwise the thread id will be saved in the queue.
My question is how i can check if the file is used by another thread ?
here is my code :
ClientFile.java
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class ClientFile {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 43333);
System.out.println(socket.getInetAddress().getHostName());
//Read and write on socket.
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//Read from console.
BufferedReader bfIn = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while ((bufferedReader.read()) != '~') {
System.out.println(bufferedReader.readLine());
}
//DemanderF
System.out.print("Enter File Id: ");
int response = bfIn.read();
printWriter.println(response);
//From ASCII TO INT.
int fileId = Character.getNumericValue(response);
//System.out.println("blabla " + fileId);
/*-----------------Receive F------------------*/
//The inputStream class will capture the streams which has been sent by the server.
InputStream inputStream = socket.getInputStream();
receiveF(inputStream, fileId);
/*---------------------------------------*/
bufferedReader.close();
printWriter.close();
socket.close();
} catch(IOException e) {
e.printStackTrace();
//System.out.println("IOException Client ---> "+ e.getStackTrace());
}
}
public static void receiveF(InputStream inputStream, int fileId)
{
try {
//Create File inside desired folder
FileOutputStream fileOutputStream = new FileOutputStream("D:\\newFile.txt");
//byte array (size of the file).
byte []b = new byte[2002];
//Read a Stream.
inputStream.read(b, 0, b.length);
//Write the whole content into file.
fileOutputStream.write(b, 0, b.length);
fileOutputStream.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
ServerFile.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.UnknownHostException;
import java.util.Arrays;
public class ServerFile {
public static void main(String[] args) {
try {
//create ServerSocket on port 43333.
ServerSocket serverSocket = new ServerSocket(43333);
while(true)
{
System.out.println("Running...");
//accept incoming Client request.
Socket clientSocket = serverSocket.accept();
System.out.println("\nClient connected");
//System.out.println("Id Client : " +clientSocket);
System.out.println("Assigning new thread for this client");
Thread t = new ClientHandler(clientSocket);
t.start();
}
} catch(UnknownHostException e) {
System.out.println("UnknownHostException ---> " + e.getMessage());
}
catch(IOException e1) {
System.out.println("IOException ---> " + e1.getMessage());
}
}
static class ClientHandler extends Thread {
Socket clientSocket;
public ClientHandler(Socket clientSocket)
{
this.clientSocket = clientSocket;
}
#Override
public void run() {
try {
//Read and write on socket.
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()), true);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//Send File list.
String directoryName = "C:\\Users\\AZZEM\\Documents\\Master 1\\Système répartis\\Files";
File file = new File(directoryName);
File fileList[] = file.listFiles();
int c = 0;
for(int i=0; i<fileList.length; i++)
{
if(fileList[i].canRead() && (fileList[i].toString().endsWith(".txt")))
{
c++;
}
//System.out.println("File list : " + fileList[i].getName() + " and Size = " + fileList[i].length() + "bytes");
}
printWriter.println(" " + c + " .txt files, listed A-Z \n");
for(int i=0; i<fileList.length; i++)
{
printWriter.println(" " + fileList[i].getName() + " and Size = " + fileList[i].length() + "bytes");
}
printWriter.println("~");
String response = bufferedReader.readLine();
int fid = Integer.parseInt(response);
//From ASCII TO INT.
int fileId = Character.getNumericValue(fid);
int threadId = (int) Thread.currentThread().getId();
System.out.println("My id is " + threadId + " and I want the file "+ fileId);
boolean isExist = false;
if(fileId >=0 && fileId<=fileList.length)
{
isExist = true;
}
else
{
isExist = false;
System.out.println("File not exist");
}
if(isExist == true)
{
System.out.println("The file " + fileId + "is used");
/*--------------------------Send File to Client------------------------------*/
File fileToSend = new File(fileList[fileId].getAbsolutePath());
FileReader fileReader = new FileReader(fileToSend);
//Read File.
FileInputStream fileInputStream = new FileInputStream(fileList[fileId].getAbsolutePath());
//Byte Array is used to include the size of the array.
byte[]b = new byte[2002];
//The read method --> Start reading the file from 0 to the end of the file (length).
//And store it in new variable which is b.
fileInputStream.read(b, 0, b.length);
//Convert file into streams.
OutputStream outputStream = clientSocket.getOutputStream();
//Send the whole file using outputStream class.
System.out.println("Sending File...");
outputStream.write(b, 0, b.length);
System.out.println("File Transferred");
fileInputStream.close();
/*---------------------------------------------------------------------------------*/
}
bufferedReader.close();
printWriter.close();
clientSocket.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}

Java seekable video stream

I'm trying made a simple video stream with Java.I got that play some mp4 video,but not all. On the other hand, I can't seek the stream when the video is playing(Tried in VLC and Chrome). I like to know: What problems does my code have?
Here is the code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Xerver {
protected void start() {
ServerSocket s;
Socket remote;
OutputStream out;
System.out.println("Webserver starting up on port 8080");
try {
// create the main server socket
s = new ServerSocket(8080);
} catch (IOException e) {
System.out.println("Error: " + e);
return;
}
System.out.println("Waiting for connection");
for (;;) {
try {
// wait for a connection
remote = s.accept();
// remote is now the connected socket
System.out.println("Connection, sending data.");
BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
FileInputStream fs;
out = remote.getOutputStream();
File file = new File("D:\\stream.mp4");
out.write("HTTP/1.0 200 OK\r\n".getBytes());
out.write("Content-Type: video/mp4\r\n".getBytes());
out.write("Accept-Ranges: bytes\r\n".getBytes());
out.write(String.format("Content-Length:%s\r\n\r\n",Long.toString(file.length())).getBytes());
fs = new FileInputStream(file);
final byte[] buffer = new byte[1024];
int count = 0;
do{
count = fs.read(buffer);
out.write(buffer, 0, count);
}
while (count <= 1024);
out.flush();
remote.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
public static void main(String args[]) {
Xerver ws = new Xerver();
ws.start();
}
}
Thanks in advance

Send file over socket (with threading on server-side) - not working

I have a Client-Server programm. The Client-programm sends a file to the server and the server receives the file. my problem is, that the file is not really receiving on the server...I't creates a file.txt in the server-directory, but it is empty...(yes i'm sure that ne file.txt in the client-directory is not empty ;) )
I think the problem is the while-loop in Client.java, because it is never embarrassed....
For the future i implements now on the server side one thread per receiving file.
The client-programm:
package controller;
public class Main {
public static void main(String[] args) {
new Controller();
}
}
-
package controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Controller {
public Controller() {
try {
sendFileToServer();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendFileToServer() throws UnknownHostException, IOException {
Socket socket = null;
String host = "localhost";
socket = new Socket(host, 5555);
String filename = "file.txt";
File file = new File(filename);
OutputStream outText = socket.getOutputStream();
PrintStream outTextP = new PrintStream(outText);
outTextP.println(filename);
long filesize = file.length();
byte[] bytes = new byte[(int) filesize];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
int count;
System.out.println("Start sending file...");
while ((count = bis.read(bytes)) > 0) {
System.out.println("count: " + count);
out.write(bytes, 0, count);
}
System.out.println("Finish!");
out.flush();
out.close();
fis.close();
bis.close();
socket.close();
}
}
-
The server-programm:
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
new Server();
}
}
-
public class Server {
private ServerSocket serverSocket;
public Server() {
try {
serverSocket = new ServerSocket(5555);
waitForClient();
} catch (IOException e) {
e.printStackTrace();
}
}
private void waitForClient() {
Socket socket = null;
try {
while(true) {
socket = serverSocket.accept();
Thread thread = new Thread(new Client(socket));
thread.start();
}
} catch (IOException ex) {
System.out.println("serverSocket.accept() failed!");
}
}
}
-
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class Client implements Runnable{
private Socket socket;
public Client(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
receiveFile();
}
private void receiveFile() {
try {
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
int bufferSize = 0;
InputStream outText = socket.getInputStream();
// Get filename
InputStreamReader outTextI = new InputStreamReader(outText);
BufferedReader inTextB = new BufferedReader(outTextI);
String dateiname = inTextB.readLine();
System.out.println("Dateiname: " + dateiname);
try {
is = socket.getInputStream();
bufferSize = socket.getReceiveBufferSize();
System.out.println("Buffer size: " + bufferSize);
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
fos = new FileOutputStream(dateiname);
bos = new BufferedOutputStream(fos);
} 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);
System.out.println("This is never shown!!!"); // In this while-loop the file is normally receiving and written to the directory. But this loop is never embarrassed...
}
bos.flush();
bos.close();
is.close();
socket.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
When you do these kind of transfers you have to keep in mind that there is a difference between a socket's close and shutdown, in your code you close the socket in the client.
So lets see what happens : you fill in the buffers then you tell the socket to close which will discard the operation you just asked for.
When you shutdown you tell the socket "I won't send more data but send what's left to be sent and shut down" so what you need to do is to shut down the socket before you close it so the data will arrive.
So instead of this
out.flush();
out.close();
fis.close();
bis.close();
socket.close();
Try it with this
out.flush();
socket.shutdownInput(); // since you only send you may not need to call this
socket.shutdownOutput(); // with this you ensure that the data you "buffered" is sent
socket.close();
Generally if you want a graceful close, you should do it like this in all cases even for the server, so what you did is usually okay if there is an error and you just close the connection since you cant recover from an error.

TCP socket communication failed after the first trial

I have received error message after the client side successful received one message from server side. The error message is: Exception in thread "main" java.net.SocketException: Software caused connection abort: recv failed
It seems in client class, line = inFromserver.readLine(); would not receive any message from server, making it become "null". But I dont know why. Could somebody please help me?
Server class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class ConcurrentServer {
public static void main(String args[]) throws IOException
{
int portNumber = 20020;
ServerSocket serverSocket = new ServerSocket(portNumber);
while ( true ) {
new ServerConnection(serverSocket.accept()).start();
}
}
}
class ServerConnection extends Thread
{
Socket clientSocket;
PrintWriter outToClient;
ServerConnection (Socket clientSocket) throws SocketException
{
this.clientSocket = clientSocket;
setPriority(NORM_PRIORITY - 1);
}
public void run()
{
BufferedReader inFromClient;
try{
inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
OutputStream outToClient = clientSocket.getOutputStream();
PrintWriter printOutPut = new PrintWriter(new OutputStreamWriter(outToClient),true);
String request= inFromClient.readLine();
if(request !=null)
{
if(!request.equalsIgnoreCase("finished"))
{
printOutPut.write("Receving data");
}
else
{
printOutPut.write("file received");
}
}
}catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
try
{
clientSocket.close();
}catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
client class
import java.io.*;
import java.net.*;
import java.util.concurrent.TimeUnit;
public class client{
public static void main(String[] args) throws Exception{
final int PORT=20020;
String serverHostname = new String("127.0.0.1");
Socket socket;
PrintWriter outToServer;
BufferedReader inFromServer;
BufferedReader inFromUser;
byte[] dataToTransfer;
String line;
int counter=0;
int i=0;
socket = new Socket(serverHostname, PORT);
outToServer = new PrintWriter(socket.getOutputStream(),true);
inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
inFromUser = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Simulation of file transferring");
System.out.println("Enter the file size you want to transfer (Max Size 50MB)");
int userInput = Integer.parseInt(inFromUser.readLine());
System.out.println("Transferring start");
boolean connection = true;
while(connection)
{
//set transfer rate at 1MB/s
dataToTransfer = new byte[1000000];
Thread.sleep(1000);
if(i<userInput)
{
outToServer.println(dataToTransfer);
counter++;
System.out.println(counter + "MB file has been transferred");
}
else
{
outToServer.println("Finished");
}
line = inFromServer.readLine();
System.out.println(line);
if(!line.equalsIgnoreCase("file received"))
{
}
else
{
System.out.println("Transfer completed");
break;
}
i++;
}
outToServer.close();
inFromServer.close();
inFromUser.close();
socket.close();
}
}
You are sending byte array from client to server and reading string on server side.
Insert somthing in your byte array and then Convert your byte array into String
String str = new String(dataToTransfer,int offset, 1000000);
then write:
outToServer.println(str);

FTP client server model for file transfer in Java

Well, I am trying to implement the ftp server and ftp client in Java. I am trying to receive a file from server. Following is line of codes. I am able to achieve Connection between server and client, but unable to send filename to server also. Well can anyone guide me whether this approach is correct or if not, please suggest proper changes.
Server's Implementation:
import java.net.*;
import java.io.*;
class MyServer {
ServerSocket ss;
Socket clientsocket;
BufferedReader fromclient;
InputStreamReader isr;
PrintWriter toclient;
public MyServer() {
String str = new String("hello");
try {
// Create ServerSocket object.
ss = new ServerSocket(1244);
System.out.println("Server Started...");
while(true) {
System.out.println("Waiting for the request...");
// accept the client request.
clientsocket = ss.accept();
System.out.println("Got a client");
System.out.println("Client Address " + clientsocket.getInetAddress().toString());
isr = new InputStreamReader(clientsocket.getInputStream());
fromclient = new BufferedReader(isr);
toclient = new PrintWriter(clientsocket.getOutputStream());
String strfile;
String stringdata;
boolean file_still_present = false;
strfile = fromclient.readLine();
System.out.println(strfile);
//toclient.println("File name received at Server is " + strfile);
File samplefile = new File(strfile);
FileInputStream fileinputstream = new FileInputStream(samplefile);
// now ready to send data from server .....
int notendcharacter;
do {
notendcharacter = fileinputstream.read();
stringdata = String.valueOf(notendcharacter);
toclient.println(stringdata);
if (notendcharacter != -1) {
file_still_present = true;
} else {
file_still_present = false;
}
} while(file_still_present);
fileinputstream.close();
System.out.println("File has been send successfully .. message print from server");
if (str.equals("bye")) {
break;
}
fromclient.close();
toclient.close();
clientsocket.close();
}
} catch(Exception ex) {
System.out.println("Error in the code : " + ex.toString());
}
}
public static void main(String arg[]) {
MyServer serverobj = new MyServer();
}
}
Client's Implementation:
import java.net.*;
import java.io.*;
class MyClient {
Socket soc;
BufferedReader fromkeyboard, fromserver;
PrintWriter toserver;
InputStreamReader isr;
public MyClient() {
String str;
try {
// server is listening on this port.
soc = new Socket("localhost", 1244);
fromkeyboard = new BufferedReader(new InputStreamReader(System.in));
fromserver = new BufferedReader(new InputStreamReader(soc.getInputStream()));
System.out.println("PLEASE ENTER THE MESSAGE TO BE SENT TO THE SERVER");
str = fromkeyboard.readLine();
System.out.println(str);
String ddd;
ddd = str;
toserver = new PrintWriter(soc.getOutputStream());
String strfile;
int notendcharacter;
boolean file_validity = false;
System.out.println("send to server" + str);
System.out.println("Enter the filename to be received from server");
strfile = fromkeyboard.readLine();
toserver.println(strfile);
File samplefile = new File(strfile);
//File OutputStream helps to get write the data from the file ....
FileOutputStream fileOutputStream = new FileOutputStream(samplefile);
// now ready to get the data from server ....
do {
str = fromserver.readLine();
notendcharacter = Integer.parseInt(str);
if (notendcharacter != -1) {
file_validity = true;
} else {
System.out.println("Read and Stored all the Data Bytes from the file ..." +
"Received File Successfully");
}
if (file_validity) {
fileOutputStream.write(notendcharacter);
}
} while(file_validity);
fileOutputStream.close();
toserver.close();
fromserver.close();
soc.close();
} catch(Exception ex) {
System.out.println("Error in the code : " + ex.toString());
}
}
public static void main(String str[]) {
MyClient clientobj = new MyClient();
}
}
The answer to the above question is :
FTP Client :
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class FileClient {
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
// localhost for testing
Socket sock = new Socket("127.0.0.1", 13267);
System.out.println("Connecting...");
InputStream is = sock.getInputStream();
// receive file
new FileClient().receiveFile(is);
OutputStream os = sock.getOutputStream();
//new FileClient().send(os);
long end = System.currentTimeMillis();
System.out.println(end - start);
sock.close();
}
public void send(OutputStream os) throws Exception {
// sendfile
File myFile = new File("/home/nilesh/opt/eclipse/about.html");
byte[] mybytearray = new byte[(int) myFile.length() + 1];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
System.out.println("Sending...");
os.write(mybytearray, 0, mybytearray.length);
os.flush();
}
public void receiveFile(InputStream is) throws Exception {
int filesize = 6022386;
int bytesRead;
int current = 0;
byte[] mybytearray = new byte[filesize];
FileOutputStream fos = new FileOutputStream("def");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
current = bytesRead;
do {
bytesRead = is.read(mybytearray, current,
(mybytearray.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while (bytesRead > -1);
bos.write(mybytearray, 0, current);
bos.flush();
bos.close();
}
}
FTP Server :
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
public static void main(String[] args) throws Exception {
// create socket
ServerSocket servsock = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
OutputStream os = sock.getOutputStream();
//new FileServer().send(os);
InputStream is = sock.getInputStream();
new FileServer().receiveFile(is);
sock.close();
}
}
public void send(OutputStream os) throws Exception {
// sendfile
File myFile = new File("/home/nilesh/opt/eclipse/about.html");
byte[] mybytearray = new byte[(int) myFile.length() + 1];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
System.out.println("Sending...");
os.write(mybytearray, 0, mybytearray.length);
os.flush();
}
public void receiveFile(InputStream is) throws Exception {
int filesize = 6022386;
int bytesRead;
int current = 0;
byte[] mybytearray = new byte[filesize];
FileOutputStream fos = new FileOutputStream("def");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
current = bytesRead;
do {
bytesRead = is.read(mybytearray, current,
(mybytearray.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while (bytesRead > -1);
bos.write(mybytearray, 0, current);
bos.flush();
bos.close();
}
}
>
Server side
import java.io.*;
import java.net.*;
class serversvi
{
public static void main(String svi[])throws IOException
{
try
{
ServerSocket servsock=new ServerSocket(105);
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the file name");
String fil=dis.readLine();
System.out.println(fil+" :is file transfer");
File myfile=new File(fil);
while(true)
{
Socket sock=servsock.accept();
byte[] mybytearray=new byte[(int)myfile.length()];
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(myfile));
bis.read(mybytearray,0,mybytearray.length);
OutputStream os=sock.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
catch(Exception saranvi)
{
System.out.print(saranvi);
}
}
}
>
Client side:
import java.io.*;
import java.net.*;
class clientsvi
{
public static void main(String svi[])throws IOException
{
try
{
Socket sock=new Socket("localhost",105);
byte[] bytearray=new byte[1024];
InputStream is=sock.getInputStream();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the file name");
String fil=dis.readLine();
FileOutputStream fos=new FileOutputStream(fil);
BufferedOutputStream bos=new BufferedOutputStream(fos);
int bytesread=is.read(bytearray,0,bytearray.length);
bos.write(bytearray,0,bytesread);
System.out.println("out.txt file is received");
bos.close();
sock.close();
}
catch(Exception SVI)
{
System.out.print(SVI);
}
}
}

Categories