How to resolve socket closed exception - java

I wrote a client server program which does the following:
1.Client sends the file to server
2.Server reads the file does some changes and sends back a message to client
3.Client should read the message
In 3rd step I am getting this error
Client program
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private static final String serverIP = "127.0.0.1";
private static final int serverPort = 3248;
private static final String fileToSend = "content.txt";
public static void main(String args[]) throws InterruptedException, UnknownHostException, IOException {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
DataOutputStream outToServer = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
clientSocket = new Socket( serverIP , serverPort );
outToServer = new DataOutputStream(clientSocket.getOutputStream());
is=clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
if (outToServer != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToServer.write(mybytearray, 0, mybytearray.length);
outToServer.flush();
outToServer.close();
// File sent, exit the main method
} catch (IOException ex) {
// Do exception handling
}
}
if(is!=null){
try {
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
System.out.println("in ");
for(byte b:baos.toByteArray()){
System.out.print(b);
}
return;
} catch (IOException ex) {
// Do exception handling
System.out.println(""+ex.getMessage());
}
finally{
clientSocket.close();
is.close();
}
}
}
}
Server Program
import java.io.*;
import java.net.*;
class TCPServer {
private static final String fileOutput = "output.txt";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
FileInputStream fromClient=null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
fromClient=(FileInputStream)connectionSocket.getInputStream();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//System.out.println(""+fromClient);
if(fromClient !=null){
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = fromClient.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = fromClient.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
connectionSocket.close();
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}

Related

send multiple files to multiple computers in java

I need to transfer few files to different computers, 1 file per 1 computer. Now i can only transfer 1 file to 1 computer. Also some computers from my IP pool can be offline, how can i avoid Exception?
Also I have all code in github:
https://github.com/xym4uk/Diplom/tree/master/src/xym4uk/test
Client
package xym4uk.test;
import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FileClient {
private static Socket sock;
private static String fileName;
private static BufferedReader stdin;
private static PrintStream ps;
public static void main(String[] args) throws IOException {
public static void sendFile(File myFile) {
//connecting
try {
sock = new Socket("localhost", 4444);
ps = new PrintStream(sock.getOutputStream());
ps.println("1");
} catch (Exception e) {
System.err.println("Cannot connect to the server, try again later.");
System.exit(1);
}
try {
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
//Sending file name and file size to the server
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
System.out.println("File " + myFile.getName() + " sent to Server.");
} catch (Exception e) {
System.err.println("File does not exist!");
}
DataBase.setRecord(sock.getInetAddress().toString(), myFile.getName());
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void receiveFile(String fileName) {
try {
sock = new Socket("localhost", 4444);
ps = new PrintStream(sock.getOutputStream());
ps.println("2");
ps.println(fileName);
} catch (Exception e) {
System.err.println("Cannot connect to the server, try again later.");
System.exit(1);
}
try {
int bytesRead;
InputStream in = sock.getInputStream();
DataInputStream clientData = new DataInputStream(in);
fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_server_" + fileName));
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
in.close();
System.out.println("File " + fileName + " received from Server.");
} catch (IOException ex) {
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server
package xym4uk.test;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
private static ServerSocket serverSocket;
private static Socket clientSocket = null;
public static void main(String[] args) throws IOException {
try {
serverSocket = new ServerSocket(4444);
System.out.println("Server started.");
} catch (Exception e) {
System.err.println("Port already in use.");
System.exit(1);
}
while (true) {
try {
clientSocket = serverSocket.accept();
System.out.println("Accepted connection : " + clientSocket.getInetAddress());
Thread t = new Thread(new CLIENTConnection(clientSocket));
t.start();
} catch (Exception e) {
System.err.println("Error in connection attempt.");
}
}
}
}
ClientConnection
package xym4uk.test;
import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CLIENTConnection implements Runnable {
private Socket clientSocket;
private BufferedReader in = null;
public CLIENTConnection(Socket client) {
this.clientSocket = client;
}
#Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String clientSelection;
while ((clientSelection = in.readLine()) != null) {
switch (clientSelection) {
case "1":
receiveFile();
break;
case "2":
String outGoingFileName;
while ((outGoingFileName = in.readLine()) != null) {
sendFile(outGoingFileName);
}
break;
default:
System.out.println("Incorrect command received.");
break;
}
in.close();
break;
}
} catch (IOException ex) {
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void receiveFile() {
try {
int bytesRead;
DataInputStream clientData = new DataInputStream(clientSocket.getInputStream());
String fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_client_" + fileName));
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
clientData.close();
System.out.println("File "+fileName+" received from client.");
} catch (IOException ex) {
System.err.println("Client error. Connection closed.");
}
}
public void sendFile(String fileName) {
try {
//handle file read
File myFile = new File(fileName);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
//handle file send over socket
OutputStream os = clientSocket.getOutputStream();
//Sending file name and file size to the client
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
System.out.println("File "+fileName+" sent to client.");
} catch (Exception e) {
System.err.println("File does not exist!");
}
}
}

Time factor in Client server program to measure upload and download time of video file

I have completed client server program to download and upload a video(media) file, but I am unable to figure out how to calculate the upload, download time separately and make it run repeatedly to measure improvement in time? I will be running client at one IP and server at different IP.
Source code of the client;
package wdc;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket("127.0.0.1", 3248);
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("C:\\file1.avi");
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
And the source code of the server side;
package wds;
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File("C:\\file2.avi");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}

TCPServer / TCP Client File transfer issue: 0 bytes

I can transfer the files but when I want to open them it says that the file is corrupted (because its 0 bytes long). T
When I start the TCPServer it waits for clients and accepts them and then sends the file to them. The client recives the file (but not all of it I assume ?) When I tried this with a picture.png that is 10 kb it worked. With anything else, it does not. I also did port forwarding (else the client couldnt get the file)
THIS IS THE TCPSERVER:
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:/Users/Tim/Desktop/P&P/Background music for P&P/Rock.wav";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3222);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(
connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File(fileToSend);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
HERE IS THE TCP CLIENT:
import java.io.*;
import java.net.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.SourceDataLine;
class TCPClient {
private final static String serverIP = "123.123.123.123";
private final static int serverPort = 3222;
private final static String fileOutput = "C:/Users/Daniel/Desktop/check.wav";
public static void main(String args[]) {
while (true) {
byte[] aByte = new byte[1024];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket(serverIP, serverPort);
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream(fileOutput);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
// Music is played here
try {
AudioInputStream input = AudioSystem
.getAudioInputStream(new File(fileOutput));
SourceDataLine line = AudioSystem.getSourceDataLine(input
.getFormat());
line.open(input.getFormat());
line.start();
byte[] buffer = new byte[1024];
int count;
while ((count = input.read(buffer, 0, 1024)) != -1) {
line.write(buffer, 0, count);
}
line.drain();
line.stop();
line.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Refactored your client code a little bit:
no need for the ByteArrayOutputStream when already using a BufferedOutputStream
use bytesRead for byte array offset
This worked for me:
if (is != null)
{
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try
{
fos = new FileOutputStream(new File(fileOutput));
bos = new BufferedOutputStream(fos);
while ((bytesRead = is.read(aByte)) != -1)
{
bos.write(aByte, 0, bytesRead);
}
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex)
{
ex.printStackTrace();
}
}

How to receive file from multiple clients?

I created a program which will send a file to the server or to clients
my problem is I have 2 clients and they both need to send a file to the server
what happens is that the server is able to receive the file only from 1 client(the one who sends the file first)
how can I resolve this problem?
here's my code:
SERVER
private void sendFile(File file)throws IOException
{
Socket socket = null;
String host = "127.0.0.1";
String receiver=txtReceiver.getSelectedItem().toString();
int port=0;
if(receiver=="Client1")
{
host="127.0.0.2";
port=4441;
}
else if(receiver=="Client2")
{
port=4442;
host="127.0.0.3";
}
else if(receiver=="Server")
{
port=4440;
host="127.0.0.1";
}
socket = new Socket(host, port);
//File file = new File("Client.txt");
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
}
byte[] bytes = new byte[(int) length];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
int count;
while ((count = bis.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.flush();
out.close();
fis.close();
bis.close();
socket.close();
}
public static void main(String args[]) throws IOException {
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(4440);
} catch (IOException ex)
{
System.out.println("Can't setup server on this port number. ");
}
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
int bufferSize = 0;
try
{
socket = serverSocket.accept();
} catch (IOException ex)
{
System.out.println("Can't accept client connection. ");
}
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("C:\\Users\\Jake_PC\\Documents\\NetBeansProjects\\OJT2\\ServerReceivables\\file.txt");
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);
}
bos.flush();
bos.close();
is.close();
socket.close();
serverSocket.close();
CLIENT
public static void main(String args[])throws IOException {
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(4441);
} catch (IOException ex)
{
System.out.println("Can't setup server on this port number. ");
}
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
int bufferSize = 0;
try
{
socket = serverSocket.accept();
} catch (IOException ex)
{
System.out.println("Can't accept client connection. ");
}
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. ");
}
//C:\Users\Jake_PC\Documents\NetBeansProjects\OJT2
try
{
fos = new FileOutputStream("C:\\Users\\Jake_PC\\Documents\\NetBeansProjects\\OJT2\\Client1Receivables\\file.txt");
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);
}
bos.flush();
bos.close();
is.close();
socket.close();
serverSocket.close();
}
private void sendFile(File file)throws IOException
{
Socket socket = null;
String host = "127.0.0.1";
String receiver=txtReceiver.getSelectedItem().toString();
int port=0;
if(receiver=="Client1")
{
port=4441;
}
else if(receiver=="Client2")
{
port=4442;
}
else if(receiver=="Server")
{
port=4440;
}
socket = new Socket(host, port);
//File file = new File("Client.txt");
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
}
byte[] bytes = new byte[(int) length];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
int count;
while ((count = bis.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.flush();
out.close();
fis.close();
bis.close();
socket.close();
}
You need to start a new thread to handle each accepted socket. Examples abound. See for example the Custom Networking trail in the Java Tutorial.

How to clear socket stream from chars in order to use it for bytes(byte file transfer)?

I'm trying to make some program which includes file transfers. Of course i have to do some client-server communication by using character streams and i need to use byte streams as well to transfer files. The problem appears when i'm using println method form PrintWriter and readLine from BufferedReader because readLine reads line but lefts '\n' on stream and that causes problem(I'm not 100% sure that that is the problem) after i try to use byte stream to transfer files. So i need to get rid off that character and i tried that by using read method from Reader class and i wasn't successful with that.
The code works perfectly without using character streamers. Pay attention how is sizeOfFile inflenced by calls of readLine.
SERVER
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static int SERVER_PORT = 9999;
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(SERVER_PORT);
System.out.println("Server je pokrenut");
while (true) {
Socket sock = ss.accept();
new MultithreadServer(sock);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
SERVER THREAD
import java.io.*;
import java.net.Socket;
import java.util.*;
public class MultithreadServer extends Thread {
private Socket sock;
BufferedReader inChar;
PrintWriter outChar;
BufferedInputStream in;
BufferedOutputStream out;
DataOutputStream outByte;
public MultithreadServer(Socket sock) throws Exception {
this.sock = sock;
inChar = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
outChar = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
sock.getOutputStream())), true);
in = new BufferedInputStream(sock.getInputStream());
out = new BufferedOutputStream(sock.getOutputStream());
outByte = new DataOutputStream(sock.getOutputStream());
start();
}
public void run() {
try {
String request = inChar.readLine();
System.out.println("Fajl: " + request);
File file = new File(request);
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(file));
long sizeOfFile = (long) file.length();
outChar.println("SOME_MESSAGE"); //PROBLEM
byte[] buffer = new byte[4096];
int len = 0;
outByte.writeLong(sizeOfFile);
long totalyTransfered = 0;
while ((len = in.read(buffer, 0, buffer.length)) !=-1) {
out.write(buffer, 0, len);
totalyTransfered += len;
}
System.out.println("Total:" + totalyTransfered);
out.flush();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
CLIENT
import java.util.*;
import java.net.*;
import java.io.*;
public class ClientServer {
static int SERVER_PORT = 9999;
public static void main(String[] args) throws Exception {
InetAddress address = InetAddress.getByName("127.0.0.1");
Socket sock = new Socket(address, SERVER_PORT);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(sock.getOutputStream())), true);
BufferedReader inChar = new BufferedReader(new InputStreamReader(sock.getInputStream()));
Reader readChar = new InputStreamReader(sock.getInputStream());
System.out.println("File:"); // choosing file from server
Scanner consoleInput = new Scanner(System.in);
String file = consoleInput.next();
out.println(file);
DataInputStream in = new DataInputStream(sock.getInputStream());
System.out.println("Type name of file:"); //choosing name for file on client
String newFile = consoleInput.next();
OutputStream outByte = new FileOutputStream(newFile);
byte[] buffer = new byte[4096];
System.out.println("aa"+inChar.readLine()+"aa"); //PROBLEM
System.out.println("SOME_TEXT"+readChar.read()+"SOME_TEXT"); //TRYING TO FIX THE PROBLEM
// in.read(); in.read(); // DIFFERENT TRY
long sizeOfFile= in.readLong(); // BUT IT STILL HAS INFLUENCE OF sizeOfFile
System.out.println("Size of file:" + sizeOfFile);
long totalyTransfered= 0;
int len = 0;
while ((len = in.read(buffer,0,buffer.length)) != -1) {
outByte.write(buffer, 0, len);
System.out.println("In one pass:" + len);
sizeOfFile-=len;
totalyTransfered+=len;
System.out.println("Total:" + totalyTransfered);
if (sizeOfFile<=0)break;
}
System.out.println("Available: "+in.available());
outByte.flush();
outByte.close();
}
}
I modified your code and made a file transfer successfully, am sorry that I didnt have time to figure the issue in your code, I thought your code was not simple :).
But please find below your modified code and its quite simple and I refered this code from here
class Server:
No changes
class ClientServer:
public class ClientServer {
static int SERVER_PORT = 9999;
private static final String fileOutput = "C:\\testout.pdf";
public static void main(String[] args) throws Exception {
InetAddress address = InetAddress.getByName("127.0.0.1");
Socket sock = new Socket(address, SERVER_PORT);
InputStream is = sock.getInputStream();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(sock.getOutputStream())), true);
BufferedReader inChar = new BufferedReader(new InputStreamReader(sock.getInputStream()));
Reader readChar = new InputStreamReader(sock.getInputStream());
System.out.println("File:"); // choosing file from server
Scanner consoleInput = new Scanner(System.in);
String file = consoleInput.next();
out.println(file);
DataInputStream in = new DataInputStream(sock.getInputStream());
System.out.println("Type name of file:"); //choosing name for file on client
//String newFile = consoleInput.next();
//
// OutputStream outByte = new FileOutputStream(newFile);
// byte[] buffer = new byte[4096];
//
//
// System.out.println("aa"+inChar.readLine()+"aa"); //PROBLEM
// System.out.println("SOME_TEXT"+readChar.read()+"SOME_TEXT"); //TRYING TO FIX THE PROBLEM
// // in.read(); in.read(); // DIFFERENT TRY
// long sizeOfFile= in.readLong(); // BUT IT STILL HAS INFLUENCE OF sizeOfFile
// System.out.println("Size of file:" + sizeOfFile);
//
// long totalyTransfered= 0;
// int len = 0;
// while ((len = in.read(buffer,0,buffer.length)) != -1) {
// outByte.write(buffer, 0, len);
// System.out.println("In one pass:" + len);
// sizeOfFile-=len;
// totalyTransfered+=len;
// System.out.println("Total:" + totalyTransfered);
// if (sizeOfFile<=0)break;
// }
// System.out.println("Available: "+in.available());
// outByte.flush();
// outByte.close();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileOutputStream fos = null;
BufferedOutputStream bos = null;
int bytesRead;
try {
byte[] aByte = new byte[1];
fos = new FileOutputStream(fileOutput);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
sock.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
class MutilthreadServer:
public class MultithreadServer extends Thread {
private Socket sock;
BufferedReader inChar;
PrintWriter outChar;
BufferedInputStream in;
BufferedOutputStream out;
DataOutputStream outByte;
public MultithreadServer(Socket sock) throws Exception {
this.sock = sock;
inChar = new BufferedReader(new InputStreamReader(sock.getInputStream()));
outChar = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
in = new BufferedInputStream(sock.getInputStream());
out = new BufferedOutputStream(sock.getOutputStream());
outByte = new DataOutputStream(sock.getOutputStream());
start();
}
public void run() {
try {
String request = inChar.readLine();
System.out.println("Fajl: " + request);
File file = new File(request);
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(file));
byte[] buffer = new byte[(int) file.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
//long sizeOfFile = (long) file.length();
//outChar.println("SOME_MESSAGE"); //PROBLEM
//byte[] buffer = new byte[4096];
try {
bis.read(buffer, 0, buffer.length);
out.write(buffer, 0, buffer.length);
out.flush();
out.close();
sock.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note: There are few unused lines of code, please remove it.
Hope it helps on a Sunday :) !!!

Categories

Resources