private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
Socket socket = new Socket(jTextField1.getText(), 15123);
OutputStream oStream = new BufferedOutputStream(socket.getOutputStream());
String name = jTextField2.getText();
DataOutputStream d = new DataOutputStream(oStream);
d.writeUTF(name);
oStream.flush();
oStream.close();
}catch(IOException e){
}
}
public static void main(String args[]) throws IOException {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new testGUI().setVisible(true);
try {
ServerSocket serverSocket3 = new ServerSocket(15123);
Socket socket3 = serverSocket3.accept();
InputStream iStream3 = socket3.getInputStream();
DataInputStream d3 = new DataInputStream(iStream3);
InetAddress ip = socket3.getInetAddress();
String t = d3.readUTF();
Socket socket1 = new Socket(ip.toString(), 3333);
OutputStream oStream1 = new BufferedOutputStream(socket1.getOutputStream());
File folder = new File("C:");
File[] listOfFiles = folder.listFiles();
for(int i = 0; i < listOfFiles.length; i++){
String filename = listOfFiles[i].getName();
String fi = d3.toString();
String[] fn = fi.split("\\.");
if(filename.startsWith(fn[0]) && listOfFiles[i].getName().endsWith(fn[1])){
DataOutputStream d1 = new DataOutputStream(oStream1);
d1.writeUTF(d3.toString());
File file1 = new File(folder.toString()+"/"+filename);
InputStream iStream1 = new FileInputStream(file1);
byte[] buffer = new byte[(int) file1.length()];
for (int readCount = iStream1.read(buffer); readCount != -1; readCount = iStream1.read(buffer)) {
oStream1.write(buffer, 0, readCount);
}
oStream1.flush();
oStream1.close();
iStream1.close();
}
}
} catch (IOException e) {
}
}
});
try {
ServerSocket serverSocket1 = new ServerSocket(3333);
Socket socket1 = serverSocket1.accept();
InetAddress ip = socket1.getInetAddress();
InputStream iStream1 = socket1.getInputStream();
DataInputStream d = new DataInputStream(iStream1);
FileOutputStream oStream1 = new FileOutputStream(d.readUTF());
byte[] buffer = new byte[8192];
int count;
while ((count = iStream1.read(buffer)) > 0) {
oStream1.write(buffer, 0, count);
}
oStream1.flush();
oStream1.getFD().sync();
oStream1.close();
iStream1.close();
JOptionPane.showMessageDialog(null, "File recived"+ip.toString(), "Notification", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
}
}
problems- (netbean code)
1)Not load GUI
2)not sending request file to another pc.
my task is; If some one request a file from someone, it search form shared location(per defined) and get the file and send it back to the requester.
need a help
Related
I have implemented a file transfer program using java socket. In this program, a file is sent from the client and its then downloaded in the Server. The program works almost correctly but the problem is the length of the received byte is always greater than the byte length sent from the client. for example, I sent 678888589 bytes from the client, but when I check the length of the received file at the server, I got 678925260 bytes. And for that reason, I am getting different checksum on the server side.
Here is my code:
Client Class:
public class Client
{
final static int ServerPort = 1234;
public static final int BUFFER_SIZE = 1024 * 50;
private static byte[] buffer;
public static void main(String args[]) throws UnknownHostException, IOException
{
Scanner scn = new Scanner(System.in);
buffer = new byte[BUFFER_SIZE];
for(int i=0;i<8;i++) {
Socket s1 = new Socket(ip, ServerPort);
DataOutputStream dos1 = new DataOutputStream(s1.getOutputStream());
SendMessage message = new SendMessage(s1, "test.mp4",dos1);
Thread t = new Thread(message);
System.out.println("Adding this client to active client list");
t.start();
}
}
}
class SendMessage implements Runnable{
String file_name;
Socket s;
public final int BUFFER_SIZE = 1024 * 50;
private byte[] buffer;
DataOutputStream dos;
public SendMessage(Socket sc,String file_name,DataOutputStream dos) {
this.file_name = file_name;
this.s=sc;
buffer = new byte[BUFFER_SIZE];
this.dos = dos;
}
#Override
public void run() {
File file = new File(file_name);
try {
sendFile(file, dos);
dos.close();
while(true) {
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
public void sendFile(File file, DataOutputStream dos) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE+1];
if(dos!=null&&file.exists()&&file.isFile())
{
FileInputStream input = new FileInputStream(file);
dos.writeLong(file.length());
System.out.println(file.getAbsolutePath());
int read = 0;
int totalLength = 0;
while ((read = input.read(buffer)) != -1) {
dos.write(buffer);
totalLength +=read;
System.out.println("length "+read);
}
input.close();
System.out.println("File successfully sent! "+totalLength);
}
}
}
Server Class
// Server class
public class Server
{
// Vector to store active clients
static Vector<ClientHandler> ar = new Vector<>();
// counter for clients
static int i = 0;
public static void main(String[] args) throws IOException
{
// server is listening on port 1234
ServerSocket ss = new ServerSocket(1234);
Socket s;
// running infinite loop for getting
// client request
while (true)
{
// Accept the incoming request
s = ss.accept();
System.out.println("New client request received : " + s);
// obtain input and output streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
System.out.println("Creating a new handler for this client...");
// Create a new handler object for handling this request.
ClientHandler mtch = new ClientHandler(s,"client " + i, dis, dos);
// Create a new Thread with this object.
Thread t = new Thread(mtch);
System.out.println("Adding this client to active client list");
// add this client to active clients list
ar.add(mtch);
// start the thread.
t.start();
// increment i for new client.
// i is used for naming only, and can be replaced
// by any naming scheme
i++;
}
}
}
// ClientHandler class
class ClientHandler implements Runnable
{
Scanner scn = new Scanner(System.in);
private String name;
final DataInputStream dis;
final DataOutputStream dos;
Socket s;
boolean isloggedin;
public static final int BUFFER_SIZE = 1024*50;
private byte[] buffer;
// constructor
public ClientHandler(Socket s, String name,
DataInputStream dis, DataOutputStream dos) {
this.dis = dis;
this.dos = dos;
this.name = name;
this.s = s;
this.isloggedin=true;
buffer = new byte[BUFFER_SIZE];
}
#Override
public void run() {
String received;
BufferedOutputStream out = null;
String outputFile = "out_"+this.name+".mp4";
BufferedInputStream in = null;
try {
in = new BufferedInputStream(s.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out = new BufferedOutputStream(new FileOutputStream(outputFile));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// while (true)
// {
try
{
long length = -1;
length = dis.readLong();
if(length!=-1)System.out.println("length "+length);
// String checkSum = dis.readUTF();
// System.out.println(checkSum);
int len=0;
long totalLength = 0;
// int len = 0;
while ((len = in.read(buffer,0,BUFFER_SIZE)) > 0) {
out.write(buffer, 0, len);
totalLength+=len;
// if(len<BUFFER_SIZE)break;
// System.out.println("length "+len);
if(len<=0)break;
}
File file = new File(outputFile);
System.out.println("total length1 "+totalLength+ " dif "+(totalLength-length));
System.out.println("output length "+file.length());
} catch (IOException e) {
e.printStackTrace();
}
}
private static String checksum(String filepath, MessageDigest md) throws IOException {
// file hashing with DigestInputStream
try (DigestInputStream dis = new DigestInputStream(new FileInputStream(filepath), md)) {
while (dis.read() != -1) ; //empty loop to clear the data
md = dis.getMessageDigest();
}
// bytes to hex
StringBuilder result = new StringBuilder();
for (byte b : md.digest()) {
result.append(String.format("%02x", b));
}
return result.toString();
}
}
It would be great if anyone can tell me what I am doing wrong. also, how can I verify the checksum on serverside. Another issue is the server side code get blocked in this block.
while ((len = in.read(buffer,0,BUFFER_SIZE)) > 0) {
out.write(buffer, 0, len);
System.out.println("length "+len);
if(len<=0)break;
}
It can't break the loop unless the client is disconnected. Although the file is recieved properly.
Regards.
You made a small mistake on the client code. You were writing out the full buffer instead of what is read from the file.
while ((read = input.read(buffer)) != -1) {
dos.write(buffer,0,read);
totalLength += read;
System.out.println("length " + read);
}
I have a problem where I want to send my file to my friend using UDP multicast, but when I try to run the code the output is this:
Output:
Exception in thread "main" java.lang.IllegalArgumentException: illegal length or offset
at java.net.DatagramPacket.setData(Unknown Source)
at java.net.DatagramPacket.<init>(Unknown Source)
at Source.createConnection(Source.java:44)
at Source.main(Source.java:102)
And this is my code:
import java.io.*;
import java.net.*;
public class Source {
private DatagramSocket socket = null;
private FE event = null;
private String sourceFilePath = "C:/joe's/file/text/hai.txt";
private String destinationPath = "C:/maria/file2/laboratory/";
private String hostname= "192.168.43.65";
public Source(){ }
public static void main1(String[] args)throws Exception
{
try
{
DatagramSocket s = new DatagramSocket();
byte[]line = new byte[100];
System.out.print("Enter text to send");
int len = System.in.read(line);
InetAddress dest = InetAddress.getByName("192.168.43.65");
DatagramPacket pkt = new DatagramPacket(line,len,dest,16900);
s.send(pkt);
s.close();
}
catch(Exception err){
System.err.println(err);
}
}
public void createConnection() {
try {
socket = new DatagramSocket();
byte[] incomingData = new byte[9999];
event = getFE();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(outputStream);
os.writeObject(event);
byte[] data = outputStream.toByteArray();
DatagramPacket sendPacket = new DatagramPacket(data, data.length, 9876);
socket.send(sendPacket);
System.out.println("File sent from AppsA");
DatagramPacket incomingPacket = new DatagramPacket(incomingData,
incomingData.length);
socket.receive(incomingPacket);
String response = new String(incomingPacket.getData());
System.out.println("Response from AppsB:" + response);
Thread.sleep(2000);
System.exit(0);
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public FE getFE() {
FE fileEvent = new FE();
String fileName = sourceFilePath.substring(sourceFilePath.lastIndexOf("/") + 1,
sourceFilePath.length());
String path = sourceFilePath.substring(0, sourceFilePath.lastIndexOf("/") + 1);
fileEvent.setDestinationDirectory(destinationPath);
fileEvent.setFilename(fileName);
fileEvent.setSourceDirectory(sourceFilePath);
File file = new File(sourceFilePath);
if (file.isFile())
{
try {
DataInputStream diStream = new DataInputStream(new FileInputStream(file));
long len = (int) file.length();
byte[] fileBytes = new byte[(int) len];
int read = 0;
int numRead = 0;
while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read,
fileBytes.length - read)) >= 0) {
read = read + numRead;
}
fileEvent.setFileSize(len);
fileEvent.setFileData(fileBytes);
fileEvent.setStatus("Success");
} catch (Exception e) {
e.printStackTrace();
fileEvent.setStatus("Error");
}
}
else {
System.out.println("path specified is not pointing to a file");
fileEvent.setStatus("Error");
}
return fileEvent;
}
public static void main(String[] args)throws Exception {
Source app = new Source();
app.createConnection();
}
}
Your problem lies in improper use of DatagramPacket constructors:
DatagramPacket sendPacket = new DatagramPacket(data, data.length, 9876);
The above line is correct however, the code below:
DatagramPacket incomingPacket = new DatagramPacket(incomingData,
incomingData.length);
Should be this:
DatagramPacket incomingPacket = new DatagramPacket(incomingData,
9876);
The second argument in the DatagramPacket constructor is the length. You initially set the length on sendPacket to 9876
Server receives a file that the client sends.
When a text file is chosen, the transfer and the writing of the file is a success, but when an image file is chosen, either the transfer or the writing of the file generates some characters not found within the original file, thus corrupting the image file. Please help :)
public class Server {
private DatagramSocket socket = null;
private DatagramPacket inPacket;
private DatagramPacket outPacket = null;
private byte[] inBuffer, outBuffer;
private final int port = 50000;
private ChooseDestination cf = new ChooseDestination();
private BufferedWriter bw;
private int receivedNo = 1;
public static void main(String[] args) {
new Server();
}
public Server(){
this.connect();
}
public void connect(){
try{
socket = new DatagramSocket(port);
String fName = "";
while(true){
inPacket = null;
// waiting for input from client
inBuffer = new byte[1024];
inPacket = new DatagramPacket(inBuffer, inBuffer.length);
socket.receive(inPacket);
// get info of client
int source_port = inPacket.getPort();
InetAddress source_address = inPacket.getAddress();
System.out.println("Client: " + source_address + " Port:" + source_port);
// converts packets received to string for content checking
String data = new String(inPacket.getData(), 0, inPacket.getLength());
if(data.contains("filename")){
System.out.println("filename set");
fName = cf.browseFolders() + data.substring(8);
System.out.println("filename: " +fName);
outBuffer = new byte[1024];
outBuffer = ("ok").getBytes();
outPacket = new DatagramPacket(outBuffer, 0, outBuffer.length, source_address, source_port);
socket.send(outPacket);
}
if (data.endsWith("ERROR!")) {
System.out.println("File doesn't exist.\n");
socket.close();
}
else if (!(data.contains("filename"))){
File file = new File(fName);
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
FileOutputStream fileOuputStream = new FileOutputStream(fName, true);
data = data.trim();
byte[] write = data.getBytes();
fileOuputStream.write(write);
fileOuputStream.close();
// sending acknowledgments formatted as ACKn where n is the packet received
outBuffer = new byte[1024];
outBuffer = ("ACK" + receivedNo + "").getBytes();
outPacket = new DatagramPacket(outBuffer, 0, outBuffer.length, source_address, source_port);
socket.send(outPacket);
receivedNo++;
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
client sends the file to the server
public class Client {
private DatagramSocket socket = null;
private DatagramPacket inPacket;
private DatagramPacket outPacket = null;
private byte[] inBuffer, outBuffer;
private final int port = 50000;
private int packetNo = 1;
public Client(){
ChooseFile cf = new ChooseFile();
String fName = cf.BrowseFilesView();
this.sendFile(fName);
}
public static void main(String[] args) {
new Client();
}
public void sendFile(String fName){
try {
InetAddress address = InetAddress.getByName("192.168.1.15");
socket = new DatagramSocket();
Path path = Paths.get(fName);
byte[] data = Files.readAllBytes(path);
outBuffer = new byte[1024];
System.out.println(fName);
String[] tag = fName.split("\\\\");
System.out.println(tag[tag.length-1]);
outBuffer = ("filename"+tag[tag.length-1]).getBytes();
outPacket = new DatagramPacket(outBuffer, 0, outBuffer.length, address, port);
socket.send(outPacket);
String s = null;
int i = 0;
int orig = 0;
while(i < data.length){
i = orig;
byte[] send = new byte[1024];
for( int ii = 0; ii < 1024 && i < data.length; ii++, i++){
send[ii] = data[i];
}
outBuffer = new byte[1024];
outBuffer = send;
outPacket = new DatagramPacket(outBuffer, 0, outBuffer.length, address, port);
socket.send(outPacket);
inBuffer = new byte[1024];
inPacket = new DatagramPacket(inBuffer, inBuffer.length);
socket.receive(inPacket);
String ack = new String(inPacket.getData(), 0, inPacket.getLength());
int ackNo = 0;
try{
ackNo = Integer.parseInt(ack.substring(3));
}
catch(Exception e){
e.printStackTrace();
}
if (packetNo == ackNo){
System.out.println(packetNo + " " + ackNo);
orig = i;
packetNo++;
}
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
i write a program client-server with multi threading for send - receive file. The program runs and client send and server receive. the files are created but empty new files are created
Why? please help me
class client :
import java.io.*;
import java.net.Socket;
public class Client extends Thread {
Socket socket = null;
Socket socket1 = null;
public void sendFile() throws IOException {
String host = "127.0.0.1";
String host1 = "127.0.0.2";
socket = new Socket(host, 1024);
socket1 = new Socket(host1, 1025);
File file = new File("/home/reza/Desktop/link help");
File file1 = new File("/home/reza/Desktop/hi");
long length = file.length();
long length1 = file1.length();
final byte[] bytes = new byte[(int) length];
final byte[] bytes1 = new byte[(int) length1];
FileInputStream fis = new FileInputStream(file);
FileInputStream fis1 = new FileInputStream(file1);
#SuppressWarnings("resource")
final BufferedInputStream bis = new BufferedInputStream(fis);
final BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
#SuppressWarnings("resource")
final BufferedInputStream bis1 = new BufferedInputStream(fis1);
final BufferedOutputStream out1 = new BufferedOutputStream(socket1.getOutputStream());
Thread t = new Thread(new Runnable() {
public void run()
{
while(socket.isConnected())
{
Wait2();
try {
System.out.println("ok");
int count;
while ((count = bis.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
Thread t1 = new Thread(new Runnable() {
public void run() {
while(socket1.isConnected())
{
Wait2();
try {
System.out.println("ok1");
int count1;
while ((count1 = bis1.read(bytes1)) > 0) {
out1.write(bytes1, 0, count1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
t1.start();
t.start();
socket.close();
socket1.close();
}
public void Wait2()
{
try {
Thread.sleep(3000);
} catch (InterruptedException x) {
System.out.println("Interrupted!");
}
}
}
class server:
import java.io.*;
import java.net.*;
public class Server {
public Server()
{
Thread t = new Thread(new Client());
t.start();
Thread t1 = new Thread(new Client());
t1.start();
}
//#SuppressWarnings("null")
public void recivefile() throws IOException {
ServerSocket serverSocket = null;
ServerSocket serverSocket1 = null;
try {
serverSocket = new ServerSocket(1024);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number. ");
}
try {
serverSocket1 = new ServerSocket(1025);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number1. ");
}
Socket socket = null;
Socket socket1 = null;
InputStream is = null;
InputStream is1 = null;
FileOutputStream fos = null;
FileOutputStream fos1 = null;
BufferedOutputStream bos = null;
BufferedOutputStream bos1 = null;
int bufferSize = 0;
int bufferSize1 = 0;
try {
socket = serverSocket.accept();
socket1 = serverSocket1.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
is = socket.getInputStream();
is1 = socket1.getInputStream();
bufferSize = socket.getReceiveBufferSize();
bufferSize1 = socket1.getReceiveBufferSize();
//bufferSize2 = socket2.getReceiveBufferSize();
System.out.println("Buffer size: " + bufferSize);
System.out.println("file recieved");
System.out.println("Buffer size1: " + bufferSize1);
System.out.println("file recieved");
System.out.println("file recieved");
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
fos = new FileOutputStream("/home/reza/Desktop/reza");
bos = new BufferedOutputStream(fos);
fos1 = new FileOutputStream("/home/reza/Desktop/ali");
bos1 = new BufferedOutputStream(fos1);
} catch (FileNotFoundException ex) {
System.out.println("File not found. ");
}
byte[] bytes = new byte[bufferSize];
int count;
while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}
byte[] bytes1 = new byte[bufferSize1];
int count1;
while ((count1 = is1.read(bytes1)) > 0) {
bos1.write(bytes1, 0, count1);
}
bos.flush();
bos.close();
bos1.flush();
bos1.close();
is.close();
is1.close();
socket.close();
serverSocket.close();
socket1.close();
serverSocket1.close();
}
public static void main(String[] args) throws IOException
{
System.out.println("server is run, please send file");
Server s = new Server();
s.recivefile();
}
}
client test class:
import java.io.IOException;
public class clientTest extends Thread {
public static void main(String[] args) throws IOException, InterruptedException
{
Client client = new Client();
client.sendFile();
}
}
I believe this code in the server to be your issue:
while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}
byte[] bytes1 = new byte[bufferSize1];
int count1;
while ((count1 = is1.read(bytes1)) > 0) {
bos1.write(bytes1, 0, count1);
}
bos.flush();
bos.close();
bos1.flush();
bos1.close();
is.close();
is1.close();
socket.close();
serverSocket.close();
socket1.close();
serverSocket1.close();
So the server has connected to the client, then it immediately checks to see if there are any bytes to read, if not it stops reading and closes the connection. If this happens faster than the client can deliver any bytes, boom, no data is received. And it WILL happend faster than the client can send data because the client is connecting THEN starting thread to send the data.
Instead, the server should read on each connection for as long as the client has maintained the connection alive. The server needs to wait for the data to be received.
Notice that in your code, the client is waiting for the server to close the connection. But how is the server supposed to know when all the data is sent? Either the client must close the connection or the client must send an EOF-type marker to the server indicating an end of the data and that it is safe to close the connection.
I'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 :) !!!