Java Connection Reset when sending .jpg or images over socket - java

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) {
...
}

Related

Java socket is stuck on readUTF()

I'm trying to transfer files over a socket in Java, my current approach for the server is:
Create new Thread
Thread sends file name using dos.writeUTF()
Thread sends file size using dos.writeLong()
Thread sends file using dos.write()
Where each Thread represents a client and dos is an instance of DataOutputStream.
Now, on the client I'm doing the same thing but reading instead of writing:
Read file name using dis.readUTF()
Read file size using dis.readLong()
Read file using dis.read()
Where dis is an instance of DataInputStream.
The problem is: when sending one file, everything goes right, but when I try to send 3 files, one after another, it looks like the server is writing everything correctly to the stream as expected but the client (After the first file, which means this starts happening from the second file) is stuck on dis.readUTF() and can't move on.
I've tried fixing this for days but can't get anything to work.
Here's the source code:
SERVER:
Main.java
public class Main {
public static void main(String[] args) {
boolean boolDebug = true;//TODO REMOVE THIS!!
ServerSocket serverSock = null;
List<Socket> clientSocks;
List<ClientThread> clientThreads;
try {
serverSock = new ServerSocket(9090);
} catch(Exception e){
e.printStackTrace();
}
clientSocks = new ArrayList<>();
clientThreads = new ArrayList<>();
ServerSocket finalServerSock = serverSock;
System.out.println();
System.out.println("Listening for incoming connections\n");
new Thread(){
#Override
public void run() {
super.run();
while (true) {
try {
Socket newSock = finalServerSock.accept();
clientSocks.add(newSock); //FIXME Remove sockets when closed
Thread thread = new ClientThread(newSock, usr, psw);
thread.start();
clientThreads.add((ClientThread)thread);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
}
ClientThread.java
public class ClientThread extends Thread {
private Socket socket;
private DataInputStream inStream;
private DataOutputStream outStream;
private String dbUser;
private String dbPassword;
public ClientThread(Socket socket, String DbUser, String DbPass) {
this.socket = socket;
this.dbUser = DbUser;
this.dbPassword = DbPass;
}
#Override
public void run() {
try {
inStream = new DataInputStream(socket.getInputStream());
outStream = new DataOutputStream(socket.getOutputStream());
sendFile("a.txt");
sendFile("b.txt");
sendFile("c.txt");
} catch (Exception e) {
e.printStackTrace();
}
}
void sendFile(String file){
try {
File f = new File(file);
outStream.writeUTF(file);
outStream.writeLong(f.length());
FileInputStream fis = new FileInputStream(f);
byte[] buffer = new byte[4096];
while (fis.read(buffer) > 0) {
outStream.write(buffer);
}
fis.close();
}catch(Exception e){
e.printStackTrace();
}
}
int getSize(byte[] buffer,long remaining){
try {
return Math.toIntExact(Math.min(((long) buffer.length), remaining));
}catch(ArithmeticException e){
return 4096;
}
}
}
CLIENT:
Main.java
class Main {
static int getSize(byte[] buffer, long remaining) {
try {
return Math.toIntExact(Math.min(((long) buffer.length), remaining));
} catch (ArithmeticException e) {
return 4096;
}
}
static void saveFile(Socket clientSock,DataInputStream dis) throws IOException {
String fileName = dis.readUTF();
File f = new File(fileName);
FileOutputStream fos = new FileOutputStream(f);
byte[] buffer = new byte[4096];
long filesize = dis.readLong();
int read = 0;
int totalRead = 0;
long remaining = filesize;
while ((read = dis.read(buffer, 0, getSize(buffer, remaining))) > 0) {
totalRead += read;
remaining -= read;
System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
}
fos.close();
}
public static void main(String[] args) throws Exception {
Socket sock = new Socket("192.168.2.17", 9090);
DataInputStream dis = new DataInputStream(sock.getInputStream());
saveFile(sock,dis);
saveFile(sock,dis);
saveFile(sock,dis);
}
}
Many thanks in advance, looking forward to fix this :(
Fixed by changing
while (fis.read(buffer) > 0) {
outStream.write(buffer);
}
to
int count;
while ((count = fis.read(buffer)) > 0) {
outStream.write(buffer, 0, count);
}
Inside ClientThread.java on the server side

Exception in thread "main" java.net.SocketException: Connection reset -

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.

java.net.ConnectException: Connection refused in TCP socket?

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.

File sending from multiple client to Single server in Java Socket Programming

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.

Sending large files (~ 1GB) fails with SocketException

I'm trying to send large files using socket programming in java for a p2p file sharing application. This code is sending 200-300 mb files without any problems, but for large files around 1 gb it is giving the error:-
java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:105)
at FileSender.main(FileSender.java:28)
I'm already sending file in small chunks as suggested in many answers I got. What should I do to send 1 gb files. I'm programming on Windows.
Here are my codes:
Server
public class FileSender {
public static void main(String...s)
{
BufferedOutputStream bos;
String file="D:\\filename.mp4";
try {
ServerSocket sock=new ServerSocket(12345);
while(true)
{
System.out.println("waiting");
Socket soc=sock.accept();
bos= new BufferedOutputStream(soc.getOutputStream());
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
int n=-1;
byte[] buffer = new byte[8192];
while((n = bis.read(buffer))>-1)
{
bos.write(buffer,0,n);
System.out.println("bytes="+n);
bos.flush();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Reciever
public class FileReciev {
public static void main(String...s)
{
try
{
Socket sock=new Socket("127.0.0.1",12345);
File file=new File("D:\\newfilename.mp4");
BufferedInputStream bis=new BufferedInputStream(sock.getInputStream());
FileOutputStream fos = new FileOutputStream(file);
int n;
byte[] buffer = new byte[8192];
System.out.println("Connected");
while ((n = bis.read(buffer)) > -1) {
System.out.println("bytes="+n);
fos.write(buffer, 0, n);
if(n<(8192)){
fos.close();
bis.close();
break;
}
fos.flush();
}
System.out.println("recieved");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
if(n<(8192)){
fos.close();
bis.close();
What this means is if you ever get less than the number of bytes that you expected, you'll shut down your socket. There's no reason to do this.

Categories

Resources