I am new to socket programming. I did a simple program to transfer zip files but that is only creating an empty zip and doesn't transfer any files. Can you help me please?
Client.java
package fileTransfer;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class SimpleClient {
public final static int SOCKET_PORT = 13267;
public final static String SERVER = "00.200.00.00";
public final static String
FILE_TO_RECEIVED = "D:/Projects/Transferred.zip";
public final static int FILE_SIZE = 6022386;
public static void main (String [] args ) throws IOException {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
try {
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = sock.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(current < FILE_SIZE);
bos.write(mybytearray, 0 , current);
bos.flush();
System.out.println("File " + FILE_TO_RECEIVED + " downloaded (" + current + " bytes read)");
}
finally {
if (fos != null) fos.close();
if (bos != null) bos.close();
if (sock != null) sock.close();
}
}
}
Server.java
package fileTransfer;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServer {
public final static int SOCKET_PORT = 13267;
public final static String FILE_TO_SEND = "C:/Users/Public/Pictures/Sample Pictures.zip";
public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// send file
File myFile = new File (FILE_TO_SEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
}
finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
}
finally {
if (servsock != null) servsock.close();
}
}
}
Kindly help me fix this!!!
Try to read file in such way on client side:
Socket s = servsock.accept();
InputStream in = s.getInputStream();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("YOUR_FILE"));
int c=0;
byte[] buff=new byte[2048];
while((c=in.read(buff))>0){ // read something from inputstream into buffer
// if something was read
bos.write(buff, 0, c);
}
in.close();
bos.close();
Do the same on the server side. Your InputStream will be a file and output will be a socket. Its robust way to copy streams.
I was finally able to transfer zip files through the socket. Please find the code below.
If anyone feels that it could be made much better. Please let me know:
Client.java
public class Client {
public final static int SOCKET_PORT = 13267;
public final static String SERVER = "00.200.00.00";
public final static String
FILE_TO_RECEIVED = "D:/Projects/Transferred.zip";
public final static int FILE_SIZE = 5830740;
public static void main(String args[]) {
int bytesRead;
int current = 0;
PrintWriter pwr=null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
BufferedReader br = null;
Socket sock = null;
String filesize= null, s=null;
try {
sock = connectToServer(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
br= new BufferedReader(new InputStreamReader(sock.getInputStream()));
pwr = new PrintWriter(sock.getOutputStream());
String input=null, output = "SENDZIP";
while((input = br.readLine()) != null){
System.out.println("INPUT is "+input);
if (input.contains("SENTZIP")){
byte [] mybytearray = new byte [Integer.parseInt(s)];
InputStream is = sock.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(current < FILE_SIZE);
bos.write(mybytearray, 0 , current);
bos.flush();
ZipFile file = new ZipFile(FILE_TO_RECEIVED) ;
System.out.println(file.size()+ " zip files are received in the client");
output = "Received"+file.size();
System.out.println(input+" when output is "+output);
pwr.println(output);
}
pwr.flush();
}
// receive file
#SuppressWarnings("resource")
ZipFile file = new ZipFile(FILE_TO_RECEIVED) ;
System.out.println(file.size()+ "in client");
System.out.println("File " + FILE_TO_RECEIVED +" has no of files "+file.size() + " downloaded (" + current + " bytes read)");
} catch (IOException e) {
System.out.println("Exception in Input Stream in Client");
e.printStackTrace();
}
finally {
if (fos != null){
try {
fos.close();
if (bos != null) bos.close();
if (sock != null) sock.close();
} catch (IOException e) {
System.out.println("Exception in closing FileOutputStream or BufferedReader or Socket");
e.printStackTrace();
}
}
}
}
public static Socket connectToServer(String server2, int socketPort) {
Socket sock = null;
try {
sock = new Socket(server2, socketPort);
} catch (IOException e) {
System.out.println("Exception in establishing connection with server");
e.printStackTrace();
}
return sock;
}
}
Server.java
public class Server
{
public final static int SOCKET_PORT = 13267;
public final static String FILE_TO_SEND = "C:/Public/Pictures/Sample Pictures.zip";
public static void main (String [] args ) throws IOException {
FileInputStream fis;
BufferedInputStream bis = null;
BufferedReader br;
OutputStream os = null;
ServerSocket servsock = null;
PrintWriter pw;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
pw = new PrintWriter(sock.getOutputStream(), true);
pw.println("SendZip");
br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
File myFile = new File (FILE_TO_SEND);
Integer i = (int) (long) myFile.getTotalSpace();
String input, output;
while ((input = br.readLine()) != null) {
System.out.println("in while loop");
if(input.equals("SENDZIP"))
{
output = "SENTZIP";
pw.println(output);
System.out.println(input+ " is the input and output is "+output);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
}
}
pw.flush();
System.out.println("Done.");
}
finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
}
finally {
if (servsock != null) servsock.close();
}
}
}
Related
I need to transfer few files to different computers, 1 file per 1 computer. Now i can only transfer 1 file to 1 computer. Also some computers from my IP pool can be offline, how can i avoid Exception?
Also I have all code in github:
https://github.com/xym4uk/Diplom/tree/master/src/xym4uk/test
Client
package xym4uk.test;
import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FileClient {
private static Socket sock;
private static String fileName;
private static BufferedReader stdin;
private static PrintStream ps;
public static void main(String[] args) throws IOException {
public static void sendFile(File myFile) {
//connecting
try {
sock = new Socket("localhost", 4444);
ps = new PrintStream(sock.getOutputStream());
ps.println("1");
} catch (Exception e) {
System.err.println("Cannot connect to the server, try again later.");
System.exit(1);
}
try {
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
//Sending file name and file size to the server
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
System.out.println("File " + myFile.getName() + " sent to Server.");
} catch (Exception e) {
System.err.println("File does not exist!");
}
DataBase.setRecord(sock.getInetAddress().toString(), myFile.getName());
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void receiveFile(String fileName) {
try {
sock = new Socket("localhost", 4444);
ps = new PrintStream(sock.getOutputStream());
ps.println("2");
ps.println(fileName);
} catch (Exception e) {
System.err.println("Cannot connect to the server, try again later.");
System.exit(1);
}
try {
int bytesRead;
InputStream in = sock.getInputStream();
DataInputStream clientData = new DataInputStream(in);
fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_server_" + fileName));
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
in.close();
System.out.println("File " + fileName + " received from Server.");
} catch (IOException ex) {
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server
package xym4uk.test;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
private static ServerSocket serverSocket;
private static Socket clientSocket = null;
public static void main(String[] args) throws IOException {
try {
serverSocket = new ServerSocket(4444);
System.out.println("Server started.");
} catch (Exception e) {
System.err.println("Port already in use.");
System.exit(1);
}
while (true) {
try {
clientSocket = serverSocket.accept();
System.out.println("Accepted connection : " + clientSocket.getInetAddress());
Thread t = new Thread(new CLIENTConnection(clientSocket));
t.start();
} catch (Exception e) {
System.err.println("Error in connection attempt.");
}
}
}
}
ClientConnection
package xym4uk.test;
import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CLIENTConnection implements Runnable {
private Socket clientSocket;
private BufferedReader in = null;
public CLIENTConnection(Socket client) {
this.clientSocket = client;
}
#Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String clientSelection;
while ((clientSelection = in.readLine()) != null) {
switch (clientSelection) {
case "1":
receiveFile();
break;
case "2":
String outGoingFileName;
while ((outGoingFileName = in.readLine()) != null) {
sendFile(outGoingFileName);
}
break;
default:
System.out.println("Incorrect command received.");
break;
}
in.close();
break;
}
} catch (IOException ex) {
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void receiveFile() {
try {
int bytesRead;
DataInputStream clientData = new DataInputStream(clientSocket.getInputStream());
String fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_client_" + fileName));
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
clientData.close();
System.out.println("File "+fileName+" received from client.");
} catch (IOException ex) {
System.err.println("Client error. Connection closed.");
}
}
public void sendFile(String fileName) {
try {
//handle file read
File myFile = new File(fileName);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
//handle file send over socket
OutputStream os = clientSocket.getOutputStream();
//Sending file name and file size to the client
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
System.out.println("File "+fileName+" sent to client.");
} catch (Exception e) {
System.err.println("File does not exist!");
}
}
}
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();
}
}
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
}
}
}
}
}
In my client server application, client sends some commands and the server gives the results back. Now the problem is when the client tries to download a file from the server, by using GET filename command. The program works fine, even it can doesnload the file correctly, but the problem is in the server side's command prompt there is always a null pointer exception error remains. And it happens immediately after I enter the GET command. Error:
Second issue appears when I remove fis.close(); line in serverside. It shows another trace error in the server side: Error:
This is the complete project I am working on:
ClientSide:
package clientside;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ClientSide {
private static Socket socket;
private static PrintWriter outputToServer;
private static BufferedReader inputFromServer;
private static InputStream is;
private static FileOutputStream fos;
private static final int PORT = 8000;
private static final String SERVER = "85.197.159.45";
boolean Connected;
DataInputStream serverInput;
public static void main(String[] args) throws InterruptedException {
String server = "localhost";
int port = PORT;
if (args.length >= 1) {
server = args[0];
}
if (args.length >= 2) {
port = Integer.parseInt(args[1]);
}
new ClientSide(server, port);
}
public ClientSide(String server, int port) {
try {
socket = new Socket(server, port);
serverInput = new DataInputStream(socket.getInputStream());
outputToServer = new PrintWriter(socket.getOutputStream(), true);
inputFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Client is connected! ");
Connected = true;
String line = null;
Scanner sc = new Scanner(System.in);
System.out.print("Type command: ");
while (sc.hasNextLine()) {
String request = sc.nextLine();
if (request.startsWith("exit")) {
outputToServer.println(request);
System.out.println("Application exited!");
//outputToServer.flush();
break;
} else if (request.startsWith("pwd")) {
outputToServer.println(request);
outputToServer.flush();
} else if (request.startsWith("list")) {
outputToServer.println(request);
outputToServer.flush();
} else if (request.startsWith("GET")) {
System.out.print("\r\n");
outputToServer.println(request);
outputToServer.flush();
}
while (Connected) {
line = inputFromServer.readLine();
System.out.println(line);
if (line.isEmpty()) {
Connected = false;
if (inputFromServer.ready()) {
System.out.println(inputFromServer.readLine());
}
}
if (line.startsWith("Status 400")) {
while (!(line = inputFromServer.readLine()).isEmpty()) {
System.out.println(line);
}
break;
}
if (request.startsWith("GET")) {
File file = new File(request.substring(4));
is = socket.getInputStream();
fos = new FileOutputStream(file);
byte[] buffer = new byte[socket.getReceiveBufferSize()];
serverInput = new DataInputStream(socket.getInputStream());
//int bytesReceived = 0;
byte[] inputByte = new byte[4000];
int length;
while ((length = serverInput.read(inputByte, 0, inputByte.length)) > 0) {
fos.write(inputByte, 0, length);
}
/*
while ((bytesReceived = is.read(buffer)) >=0) {
//while ((bytesReceived = is.read(buffer))>=buffer) {
fos.write(buffer, 0, bytesReceived);
}
*/
request = "";
fos.close();
is.close();
}
}
System.out.print("\nType command: ");
Connected = true;
}
outputToServer.close();
inputFromServer.close();
socket.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
ServerSide:
package serverside;
import java.io.*;
import java.net.*;
import java.util.Arrays;
public class ServerSide {
private BufferedReader inputFromClient;
private PrintWriter outputToClient;
private FileInputStream fis;
private OutputStream os;
private static final int PORT = 8000;
private ServerSocket serverSocket;
private Socket socket;
public static void main(String[] args) {
int port = PORT;
if (args.length == 1) {
port = Integer.parseInt(args[0]);
}
new ServerSide(port);
}
private boolean fileExists(File[] files, String filename) {
boolean exists = false;
for (File file : files) {
if (filename.equals(file.getName())) {
exists = true;
}
}
return exists;
}
public ServerSide(int port) {
// create a server socket
try {
serverSocket = new ServerSocket(port);
} catch (IOException ex) {
System.out.println("Error in server socket creation.");
System.exit(1);
}
while (true) {
try {
socket = serverSocket.accept();
os = socket.getOutputStream();
outputToClient = new PrintWriter(socket.getOutputStream());
inputFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String request = inputFromClient.readLine();
if (!request.startsWith("exit") && !request.startsWith("pwd") && !request.startsWith("list") && !request.startsWith("GET")) {
outputToClient.println("Wrong request\r\n"
+ "\r\n");
} else if (request.startsWith("exit")) {
break;
} else if (request.startsWith("pwd")) {
File file = new File(System.getProperty("user.dir"));
outputToClient.print("Status OK\r\n"
+ "Lines 1\r\n"
+ "\r\n"
+ "Working dir: " + file.getName() + "\r\n");
} else if (request.startsWith("list")) {
File file = new File(System.getProperty("user.dir"));
File[] files = file.listFiles();
outputToClient.print("Status OK\r\n"
+ "Files " + files.length + "\r\n"
+ "\r\n"
+ Arrays.toString(files).substring(1, Arrays.toString(files).length() - 1) + "\r\n");
} else if (request.startsWith("GET")) {
String filename = request.substring(4);
File file = new File(System.getProperty("user.dir"));
File[] files = file.listFiles();
if (fileExists(files, filename)) {
file = new File(filename);
int fileSize = (int) file.length();
outputToClient.printf("Status OK\r\nSize %d Bytes\r\n\r\nFile %s Download was successfully\r\n",
fileSize, filename);
outputToClient.flush();
try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[(1 << 7) - 1];
int bytesRead = 0;
while ((bytesRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
}
os.close();
fis.close();//NPE is happening here.
} else {
outputToClient.print("Status 400\r\n"
+ "File " + filename + " not found\r\n"
+ "\r\n");
outputToClient.flush();
}
}
outputToClient.flush();
}
} catch (IOException e) {
System.err.println(e);
}
finally{
os.close();
}
}
}
}
UPDATE: Even if I remove the fis.close(); line from the server side, it shows java.net.SocketException: socket closed error.
The original problem is that you are using a try-with-resources block with an assigned variable with the same name as one of your class member variables. Removing the following line will remove the NPE:
fis.close();
The SocketException is being caused by the line:
os.close();
According to the documentation of Socket::getOutputStream:
Closing the returned OutputStream will close the associated socket.
Therefore, moving the line os = socket.getOutputStream(); to just below the line socket = serverSocket.accept(); line, and also moving os.close() to a finally block after your final catch block should solve this issue.
The socket represented by fis is null.
To correct, use this:
if (fis != null) fis.close;
try (FileInputStream fis = new FileInputStream(file))
In this line you are creating a new FileInputStream and using it, and it is not your FileInputStream field, declared before. This fis exists only on the "try" block. When you try to close your fis os.close(); you are trying to close your fis field, not the fis declared in the try.
Use this, instead:
try (fis = new FileInputStream(file)). With this you are instantiating a new FileInputStream in your field, not in a new variable.
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 :) !!!