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

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.

Related

Java Connection Reset when sending .jpg or images over socket

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

FileNotFound Exception in FileOutputStream

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.

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.

Java multithreaded server socket

I tried to create a multithread server socket. It can either send a string for available file or a file as a stream.
The problem is the else block, which sends requested file as a stream, works once. Where is the problem in my code and why it replies just once?
public class ServerThread extends Thread {
Socket socket = null;
public ServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
String message = null;
PrintStream ps = null;
String string = null;
File file = null;
BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ps = new PrintStream(socket.getOutputStream());
while ((message = bufferedreader.readLine()) != null) {
if (message.equals("list")) {
ps.println(Arrays.toString(getServerFiles()));
} else {
message = "FilesServer\\" + message;
file = new File(message);
//JOptionPane.showConfirmDialog(null, message);
if (file.exists()) {
BufferedInputStream bfInStream =
new BufferedInputStream(new FileInputStream(message));
BufferedOutputStream bufOutStream =
new BufferedOutputStream(socket.getOutputStream());
byte[] buffer = new byte[1024];
int read = 0;
while ((read = bfInStream.read(buffer)) != -1) {
bufOutStream.write(buffer, 0, read);
bufOutStream.flush();
}
bufOutStream.close();
System.out.println("File transfered");
}
}
}
} catch (Exception e) {
//JOptionPane.showConfirmDialog(null, e.getMessage());
}
}
private static String[] getServerFiles() {
String result[];
File folder = new File("FilesServer\\");
File[] listOfFiles = folder.listFiles();
result = new String[listOfFiles.length];
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
result[i] = listOfFiles[i].getName();
}
}
return result;
}
}
Above class is called from this class:
public class Server {
private int defaultPort = 8088;
public static void main(String[] args) throws IOException {
new Server().InitServer();
}
private void InitServer() throws IOException{
ServerSocket serversocket = new ServerSocket(8081);
while(true){
Socket socket = serversocket.accept();
new ServerThread(socket).start();
}
}
}
For server applications, you should use ServerSocket. ServerSocket must create new Socket each time new client requested a file (via accept() method). Then you send bytes into newly created socket and can safely close it.
Do not open and close the BufferedOutputStream bufOutStream. instead write directly to ps and close this after the while-loop.
closing bufOutStream closes the socket as MadProgrammer already mentioned.

Java client app freezes when sending object through sockets

i have this client/server application, and the client application sometimes completely freezes when i try send object via sockets
public Client client = new Client();
petriNetList = client.query(client.actionLoadPetriNetList, MainWindow.loginUsername);
here is the code of the client
public class Client {
public static Socket kkSocket = null;
public static PrintWriter out = null;
public static BufferedReader in = null;
public static BufferedReader stdIn = null;
public static OutputStream outputStream = null ;
public static ObjectOutputStream objectOutputStream = null ;
public static InputStream inputStream = null ;
public static ObjectInputStream objectInputStream = null ;
public String actionSavePetriNet = "SAVE PETRI NET START";
/*
* Save petri net to server
*
* #param action identifies query
* #param petriName name of the petri net
* #param username username
* #param xml content of the petri net
*
* #return int response form server
*/
public int query (String action,String petriName,String username,String xml) throws IOException {
int size ;
int result = 0;
connect();
if (action.equals(actionSavePetriNet)) {
out.println(action); // save petri net
out.println(petriName); //petri net name
out.println(username); //username
System.out.println("(Client:)" + xml);
objectOutputStream.writeObject(xml); //send object over the network
System.out.println("Dostali sme sa sem ?");
result = Integer.parseInt(in.readLine()); //read response from server
}
disconnect();
return result;
}
/*
* connect to server
* TODO: ADD hostname and port as parameter
*/
public static void connect() throws IOException {
try {
kkSocket = new Socket("osiris-PC", 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: taranis.");
System.exit(1);
}
stdIn = new BufferedReader(new InputStreamReader(System.in));
outputStream = kkSocket.getOutputStream();
objectOutputStream = new ObjectOutputStream(outputStream);
inputStream = kkSocket.getInputStream();
objectInputStream = new ObjectInputStream(inputStream);
}
/*
* Disconnect from server
* close all input/output streams
*
*/
public static void disconnect() throws IOException {
out.close();
in.close();
stdIn.close();
objectOutputStream.close();
outputStream.close();
objectInputStream.close();
inputStream.close();
kkSocket.close();
}
}
and this is the code of server
public class PetriServer {
public static Protocol kkp = new Protocol();
public static InputStream inputStream = null ;
public static ObjectInputStream objectInputStream = null ;
public static OutputStream outputStream = null ;
public static ObjectOutputStream objectOutputStream = null ;
public static void main(String[] args) throws IOException, ClassNotFoundException {
kkp.loadUsers();
while(true) {
ServerSocket serverSocket = null;
inputStream = null ;
objectInputStream = null ;
outputStream = null ;
objectOutputStream = null ;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
inputStream = clientSocket.getInputStream();
objectInputStream = new ObjectInputStream(inputStream);
outputStream = clientSocket.getOutputStream();
objectOutputStream = new ObjectOutputStream(outputStream);
inputLine = in.readLine();
String inputLine;
if (inputLine.equals("SAVE PETRI NET START")) {
String petriName;
String username;
String xml ;
String input;
int result;
int size ;
petriName = in.readLine(); //read petri name
System.out.println("(Server): prijali sme poziadavok na ulozenie " + petriName );
username = in.readLine(); //read username
System.out.println("(Server): poziadavok ide od usera: " + username);
while(true) {
//this is the line where is occasionally freezes
xml = (String)objectInputStream.readObject(); //read object over the network
if (!xml.isEmpty()) break;
}
System.out.println("(Server):" + xml);
result = kkp.savePetrinet(username, petriName,xml); //save it to the file
out.println(result);
}
out.close();
in.close();
objectInputStream.close();
inputStream.close();
objectOutputStream.close();
outputStream.close();
clientSocket.close();
serverSocket.close();
}
}
}
Does anybody know what can be problem ?
cheers.
You have the Socket InputStream on the server attached to two different inputs, ObjectInputStream and BufferedReader. InputStreams are not intended to be used this way, and doing so can cause a lot of problems. BufferedReaders, by their nature, are going to be pulling more data off the InputStream than you are actually reading. If they happen to buffer data that makes up an object, then your subsequent attempt to read the object off the ObjectInputStream will block, because the data has already been removed.
You need to pick one method or the other to read data. If you need to be able to read both Strings and Objects off the Socket, then you will have to go to a byte-oriented mode of operation where you read the bytes off into a byte array, then process the byte array yourself to insure that you don't loose any data.
Edit based on #Dunes comment below
Seems your best bet is to stick entirely with ObjectInputStream and make use of its other methods that allow you to read arbitrary primitive types from the stream. And, if you don't mind the deprecated call, it even has a readLine method.

Categories

Resources