Connection reset by peer: socket write error, when Transferring Large File - java

I'm making a program which transfers a file. In the process of this method, I'm getting the written error:
"Connection reset by peer: socket write error"
The file's size which I'm transferring is 96MB.
(clientSocket is SSLSocket)
Client:
Activity_1 Class:
clientSocket = (SSLSocket) sslContext.getSocketFactory().createSocket();
clientSocket.connect(...);
clientSocket.setEnabledCipherSuites(clientSocket.getSupportedCipherSuites());
clientSocket.startHandshake();
Activity_2 Class:
SSLSocket clientSocket = Activity_1.clientSocket;
final DataInputStream dis = new DataInputStream(clientSocket.getInputStream());
int n = 0;
final byte[] buf = new byte[8192];
fos = new new FileOutputStream....
while ((n = dis.read(buf)) != -1) {
counter += n;
fos.write(buf, 0, n);
runOnUiThread(new Runnable() {
#Override
public void run() {
...
}
});
}
if (counter >= file_size) {
System.out.println("CLOSED");
fos.flush();
fos.close();
clientSocket.close();
}
Server:
FileInputStream fis = new FileInputStream...
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
byte[] mybytearray = new byte[8192];
OutputStream os;
try {
os = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
int read = -1;
while ((read = dis.read(mybytearray)) > -1) {
dos.write(mybytearray, 0, read);
}
System.out.println("CLOSED");
dos.flush();
dos.close();
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
What could cause this problem to occur?
Thanks in advanced.

Related

Android:java.lang.OutOfMemoryError Failed to allocate a 360318346 byte allocation with 5802592 free bytes and 87MB until OOM

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.

Transfer file from client to server over socket in java

I am trying to upload a file from a client to the server using sockets in JAVA. It is partially working, however, the file that gets created on the server is an empty text file. Can anyone offer any suggestions as to where I may have an issue. Thanks:
Server:
private void handleFileUpload(String fileSizeInBytes, String fileName) throws IOException{
String fullyQualifiedFileName = rootDirectory+System.getProperty("file.separator")+fileName;
File fileToWrite = new File(fullyQualifiedFileName);
if(fileToWrite.exists()){
fileToWrite.delete();
}
int bytesRead = 0;
byte[] aByte = new byte[1];
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
ByteArrayOutputStream baos = null;
try {
inputStream = socket.getInputStream();
fileOutputStream = new FileOutputStream(fullyQualifiedFileName);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bytesRead = inputStream.read(aByte, 0, aByte.length);
baos = new ByteArrayOutputStream();
do {
baos.write(aByte);
bytesRead = inputStream.read(aByte);
} while (bytesRead != -1);
bufferedOutputStream.write(baos.toByteArray());
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Client:
private void uploadFile(Socket socket, File fileToUpload){
byte[] mybytearray = new byte[(int) fileToUpload.length()];
try {
FileInputStream fis = new FileInputStream(fileToUpload);
BufferedOutputStream toServer = new BufferedOutputStream(socket.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
toServer.write(mybytearray, 0, mybytearray.length);
toServer.flush();
toServer.close();
return;
} catch (IOException ex) {
handleServerError("upload file", ex);
System.exit(0);
}
Change your handleFileUpload method as following
private void handleFileUpload(String fileSizeInBytes, String fileName) throws IOException{
String fullyQualifiedFileName = rootDirectory+System.getProperty("file.separator")+fileName;
File fileToWrite = new File(fullyQualifiedFileName);
if(fileToWrite.exists()){
fileToWrite.delete();
}
int bytesRead = 0;
byte[] aByte = new byte[1024];
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
ByteArrayOutputStream baos = null;
try {
inputStream = socket.getInputStream();
fileOutputStream = new FileOutputStream(fullyQualifiedFileName);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bytesRead = inputStream.read(aByte, 0, aByte.length);
while (bytesRead != -1) {
bufferedOutputStream.write(aByte, 0, bytesRead);
bytesRead = inputStream.read(aByte, 0, aByte.length);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

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 resolve socket closed exception

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
}
}
}
}
}

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.

Categories

Resources