hi i am trying to create a program in java for sending files from multiple client to single server. is this is possible?
i tried this could for multiple client and single server and also it is from server to client sending program.
Client Program
public class Client {
public Client(String ip,String path,int i) throws IOException {
int filesize=2022386;
int bytesRead;
int currentTot = 0;
File file=new File(path);
File dir=new File("c:/PAMR/Dest"+i+"/");
String name=file.getName();
if(!dir.exists())
{
dir.mkdir();
}
Socket socket = new Socket(ip,9100);
byte [] bytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(dir+"/"+name);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead;
do {
bytesRead =
is.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead >= 0) currentTot += bytesRead;
} while(bytesRead > -1);
bos.write(bytearray, 0 , currentTot);
bos.flush();
bos.close();
socket.close();
}
}
for Server
public class Source {
public Source(String path) throws IOException {
ServerSocket serverSocket = new ServerSocket(9100);
System.out.println("Server is in Listening Mode");
Socket socket = serverSocket.accept();
File transferFile = new File (path);
byte [] bytearray = new byte [(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray,0,bytearray.length);
OutputStream os = socket.getOutputStream();
os.write(bytearray,0,bytearray.length);
bin.close();
os.close();
os.flush();
socket.close();
serverSocket.close();
}
}
it is a part of code for my project i am doing.
Any body pls help.
You want something like this:
boolean working = true;
ServerSocket ss = new ServerSocket(9100);
while(working) {
Socket s = ss.accept();
MyThread myThread = new MyThread(s);
myTread.start();
}
where MyThread is a class of yours that extends the Thread class, accepts the connection to the client that just connected and then accepts any file or data sent to it.
Related
I have no problems sending large text documents, or other files over sockets with my java program, but when I try to send a .jpg file or other image I get java.net.SocketException: Connection reset.
I have not run into any trouble when sending a 229 KB text document over the socket, but when I try to send the 89 KB image, I get the error. I use a while loop to read and write the file.
This is the part of the server class in question (it is named EasyDataSend):
public EasyDataSend() throws IOException
{
port = 8080;
server = new ServerSocket(port);
socket = server.accept();
dataOutputStream = new DataOutputStream(socket.getOutputStream());
}
public void sendFile(String path) throws IOException
{
File file = new File(path);
InputStream fileInputStream = new FileInputStream(file);
OutputStream fileOutputStream = socket.getOutputStream();
byte[] bytes = new byte[16 * 1024];
int count;
while ((count = fileInputStream.read(bytes)) > 0)
{
fileOutputStream.write(bytes, 0, count);
}
fileOutputStream.close();
fileInputStream.close();
socket.close();
server.close();
}
And this is the part of the client class (name EasyDataReceive):
public EasyDataReceive() throws UnknownHostException, IOException
{
ip = "127.0.0.1";
port = 8080;
socket = new Socket(ip,port);
}
public void receiveFile(String path) throws IOException, SocketException
{
File file = new File(path);
InputStream fileInputStream = socket.getInputStream();
OutputStream fileOutputStream = new FileOutputStream(file);
byte[] bytes = new byte[16*1024];
int count;
while ((count = fileInputStream.read(bytes)) > 0)
{
fileOutputStream.write(bytes, 0, count);
}
fileOutputStream.close();
fileInputStream.close();
socket.close();
}
This is the error I get:
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at EasyDataReceive.receiveFile(EasyDataReceive.java:111)
at TesterClient.main(TesterClient.java:23)
Also, the line 111 is really just the start of the while loop in the client class. I did not want to paste the whole class into the post. The line 23 is just part of the testing class where I construct the EasyDataReceive object.
Your socket should be inside the methods: receiveFile() and sendFile().
For example,
public static void sendFile(String path) throws IOException {
try {
socket = new Socket("127.0.0.1", 8080);
System.out.println("Connected");
File file = new File(path);
InputStream fileInputStream = new FileInputStream(file);
OutputStream fileOutputStream = socket.getOutputStream();
byte[] bytes = new byte[16 * 1024];
int count;
while ((count = fileInputStream.read(bytes)) > 0) {
fileOutputStream.write(bytes, 0, count);
}
fileOutputStream.close();
fileInputStream.close();
} catch (UnknownHostException u) {
System.out.println(u);
} catch (IOException i) {
System.out.println(i);
} finally {
try {
socket.close();
} catch (IOException i) {
System.out.println(i);
}
}
}
Or you should pass the socket client to your method, i.e.
private void receiveFile (Socket client) {
...
}
I'm getting error of FileNotFound. Basically, I'm trying to upload file from client to server.
Please, help me with it.
This is client.java class
package ftppackage;
import java.net.*;
import java.io.*;
public class Client {
public static void main (String [] args ) throws IOException {
Socket socket = new Socket("127.0.0.1",15123);
File transferFile = new File ("D:\\AsiaAd.wmv");
byte [] bytearray = new byte [(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray,0,bytearray.length);
OutputStream os = socket.getOutputStream();
System.out.println("Sending Files...");
os.write(bytearray,0,bytearray.length);
os.flush();
socket.close();
System.out.println("File transfer complete");
}
}
And this is my server.java class
package ftppackage;
import java.net.*;
import java.io.*;
public class Server {
public static void main (String [] args ) throws IOException {
int filesize=1022386;
int bytesRead;
int currentTot = 0;
ServerSocket serverSocket = new ServerSocket(15123);
Socket socket = serverSocket.accept();
System.out.println("Accepted connection : " + socket);
byte [] bytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("E:\\0\\"); // it is creating new file not copying the one from client
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead;
do {
bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead >= 0)
currentTot += bytesRead;
} while(bytesRead > -1);
bos.write(bytearray, 0 , currentTot);
bos.flush();
bos.close();
socket.close();
}
}
Plus, guide me how do add progress bar in it with percentage. I read about SwingWorker here but unable to implement it as I'm totally new with threading concepts.
Thank you for considering my questions.
FileNotFoundException is something you will get if you point the File Object to some File which is not existing in that path. it means what ever the file you are trying to upload in not there in the specified path. SO make sure you give a valid path.
I am working on transfer file from server to client example.When i am trying to transfer large file (in example i have 500mb video file) then it shows error Android:java.lang.OutOfMemoryError Failed to allocate a 360318346 byte allocation with 5802592 free bytes and 87MB until OOM. Please help me how to solve this error.
Server side some peace of code
public class FileTxThread extends Thread {
Socket socket;
FileTxThread(Socket socket){
this.socket= socket;
}
#Override
public void run() {
File file = new File(Environment.getExternalStorageDirectory(),"RAHASYA.mp4");
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream bis;
try {
bis = new BufferedInputStream(new FileInputStream(file));
bis.read(bytes, 0, bytes.length);
OutputStream os = socket.getOutputStream();
os.write(bytes, 0, bytes.length);
os.flush();
// socket.close();
final String sentMsg = "File sent to: " + socket.getInetAddress();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,sentMsg,Toast.LENGTH_LONG).show();
}});
Client side some peace of code
private class ClientRxThread extends Thread {
String dstAddress;
int dstPort;
ClientRxThread(String address, int port) {
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
out.println("Sockt "+socket.getInetAddress());
File file = new File(Environment.getExternalStorageDirectory(),"RAHASYA.mp4");
byte[] bytes = new byte[1024];
InputStream is = socket.getInputStream();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
while (true) {
int bytesRead = is.read(bytes);
if (bytesRead < 0) break;
bos.write(bytes, 0, bytesRead);
// Now it loops around to read some more.
}
bos.close();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,"Finished",Toast.LENGTH_LONG).show();
}});
your byte array on server side is too large , change it smaller and try ?
for reference:
File file = new File(Environment.getExternalStorageDirectory(),"RAHASYA.mp4");
byte[] bytes = new byte[2048];
BufferedInputStream bis;
try {
bis = new BufferedInputStream(new FileInputStream(file));
OutputStream os = socket.getOutputStream();
int read = bis.read(bytes, 0, bytes.length);
while (read!=-1){
os.write(bytes, 0, read);
os.flush();
read = bis.read(bytes, 0, bytes.length);
}
//...and so on
Your problem is the line
byte[] bytes = new byte[(int) file.length()];
You are creating an array of the size of the whole file. You need to read a bit at a time.
I have created a simple Client/Server program where the client takes a file from command line arguments. The client then sends the file to the server, where it is compressed with GZIP and sent back to the client.
The server program when ran first is fine, and produces no errors but after running the client I get the error.
I am getting an error saying the connection is reset, and i've tried numerous different ports so i'm wondering if there is something wrong with my code or time at which i've closed the streams?
Any help would be greatly appreciated!
EDIT - Made changes to both programs.
Client:
import java.io.*;
import java.net.*;
//JZip Client
public class NetZip {
//Declaring private variables.
private Socket socket = null;
private static String fileName = null;
private File file = null;
private File newFile = null;
private DataInputStream fileIn = null;
private DataInputStream dataIn = null;
private DataOutputStream dataOut = null;
private DataOutputStream fileOut = null;
public static void main(String[] args) throws IOException {
try {
fileName = args[0];
}
catch (ArrayIndexOutOfBoundsException error) {
System.out.println("Please Enter a Filename!");
}
NetZip x = new NetZip();
x.toServer();
x.fromServer();
}
public void toServer() throws IOException{
while (true){
//Creating socket
socket = new Socket("localhost", 4567);
file = new File(fileName);
//Creating stream to read from file.
fileIn = new DataInputStream(
new BufferedInputStream(
new FileInputStream(
file)));
//Creating stream to write to socket.
dataOut = new DataOutputStream(
new BufferedOutputStream(
socket.getOutputStream()));
byte[] buffer = new byte[1024];
int len;
//While there is data to be read, write to socket.
while((len = fileIn.read(buffer)) != -1){
try{
System.out.println("Attempting to Write " + file
+ "to server.");
dataOut.write(buffer, 0, len);
}
catch(IOException e){
System.out.println("Cannot Write File!");
}
}
fileIn.close();
dataOut.flush();
dataOut.close();
}
}
//Read data from the serversocket, and write to new .gz file.
public void fromServer() throws IOException{
dataIn = new DataInputStream(
new BufferedInputStream(
socket.getInputStream()));
fileOut = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(
newFile)));
byte[] buffer = new byte[1024];
int len;
while((len = dataIn.read(buffer)) != -1){
try {
System.out.println("Attempting to retrieve file..");
fileOut.write(buffer, 0, len);
newFile = new File(file +".gz");
}
catch (IOException e ){
System.out.println("Cannot Recieve File");
}
}
dataIn.close();
fileOut.flush();
fileOut.close();
socket.close();
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.zip.GZIPOutputStream;
//JZip Server
public class ZipServer {
private ServerSocket serverSock = null;
private Socket socket = null;
private DataOutputStream zipOut = null;
private DataInputStream dataIn = null;
public void zipOut() throws IOException {
//Creating server socket, and accepting from other sockets.
try{
serverSock = new ServerSocket(4567);
socket = serverSock.accept();
}
catch(IOException error){
System.out.println("Error! Cannot create socket on port");
}
//Reading Data from socket
dataIn = new DataInputStream(
new BufferedInputStream(
socket.getInputStream()));
//Creating output stream.
zipOut= new DataOutputStream(
new BufferedOutputStream(
new GZIPOutputStream(
socket.getOutputStream())));
byte[] buffer = new byte[1024];
int len;
//While there is data to be read, write to socket.
while((len = dataIn.read(buffer)) != -1){
System.out.println("Attempting to Compress " + dataIn
+ "and send to client");
zipOut.write(buffer, 0, len);
}
dataIn.close();
zipOut.flush();
zipOut.close();
serverSock.close();
socket.close();
}
public static void main(String[] args) throws IOException{
ZipServer run = new ZipServer();
run.zipOut();
}
}
Error Message:
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:196)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
at java.io.DataInputStream.read(DataInputStream.java:100)
at ZipServer.<init>(ZipServer.java:38)
at ZipServer.main(ZipServer.java:49)
First, the error occurs because the client fails and ends before sending any data, so that
the connection is closed at the time the server wants to read.
The error occurs because you assign the File objects to unused local variables (did your compiler not warn?)
public File file = null;
public File newFile = null;
public static void main(String[] args) throws IOException {
try {
String fileName = args[0];
File file = new File(fileName);
File newFile = new File(file +".gz");
}
catch (ArrayIndexOutOfBoundsException error) {
System.out.println("Please Enter a Filename!");
}
but In your toServer method you use the class variable file as parameter for FileInputStream and this variable is null and this results in an error which ends the program.
Second, if you finished the writing to the outputstream, you should call
socket.shtdownOutput();
Otherwise, the server tries to read until a timeout occurs.
Problem is that server is not able to download apache maven.
So what you can do is just copy the apache maven folder and paste it in the wrapper folder inside the project.
It will manually download the apache maven, and it will definitely work.
I have created a program to send file from client to server but when i am running that file in localhost it works good and i can send the file but when i am sending that file from another PC to my PC it shows "java.net.ConnectException: Connection refused".
Port number at both side same and firewall is also off. Even port is listening when client request to connect server socket is also accepting the socket.
Thank you in advance
Code of my program is :
public class ProgramSocket {
public ProgramSocket(ServerSocket servsock) throws IOException {
System.out.print("server started");
while (true) {
final Socket sock;
try {
sock = servsock.accept();
} catch (SocketException e) {
break;
}
new Thread(new Runnable() {
#Override
public void run() {
try {
connectToNewClient(sock);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
System.out.print("server stopped");
}
void connectToNewClient(Socket sock) throws IOException,
InterruptedException {
FileOutputStream fos = new FileOutputStream("C:/abc.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
bos.close();
sock.close();
}
}
Client side :
public String uploadFile(String filePath) throws Exception {
Socket sock = new Socket(ip, 24999);
// select file
File myFile = new File(filePath);
// send the program file
byte[] mybytearray = new byte[(int) myFile.length()];
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(myFile));
OutputStream os = sock.getOutputStream();
bis.read(mybytearray, 0, mybytearray.length);
os = sock.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
bis.close();
sock.close();
return message;
}
omitted some code for brevity.