I am writing tcp client-server program. When the client types "Hello" the server returns a list of files and directories of his current directory. When the client types "FileDownload " it downloads the selected file from the server.
When I type "Hello" it works fine, but when I type "FileDownload ", on the server side it runs twice the else if(received.contains("FileDownload")) block. Because of this the server is sending twice the data which is causing other issues on the client side.
Here is the server code:
public static void main(String[] args) throws IOException {
ServerSocket servSock = new ServerSocket(1333);
String received="";
String[] s = null;
File[] f1;
int i=0;
File f=new File(System.getProperty("user.dir"));
f1=f.listFiles();
for(File f2:f1) {
if(f2.isDirectory())
System.out.println(f2.getName() + "\t<DIR>\t" + i);
if(f2.isFile())
System.out.println(f2.getName() + "\t<FILE>\t" + i);
i++;
}
while (true) {
Socket client = servSock.accept();
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
PrintWriter pw = new PrintWriter(out, true);
s=f.list();
while(true) {
received = reader.readLine();
if(received.equals("END")) break;
if(received.equals("Hello")) {
System.out.println("Hello-Start");
int length=f1.length;
pw.println(length);
i=0;
for(File f2:f1) {
if(f2.isDirectory())
pw.println(f2.getName() + "\t<DIR>\t" + i);
if(f2.isFile())
pw.println(f2.getName() + "\t<FILE>\t" + i);
i++;
}
pw.println("Options: " + "\tFileDownload <FID>" + "\tFileUpload <name>" + "\tChangeFolder <name>");
System.out.println("Hello-End");
}
else if(received.contains("FileDownload")) {
System.out.println("FileDownload-Start");
int j=-1;
try {
j=Integer.parseInt(received.substring(13).trim());
}catch(NumberFormatException e) {
System.err.println("error: " + e);
}
if(j>0 && j<s.length) {
FileInputStream fi=new FileInputStream(s[j]);
byte[] b=new byte[1024];
System.out.println("file: "+s[j]);
pw.println(s[j]);
fi.read(b,0,b.length);
out.write(b,0,b.length);
System.out.println("FileDownload-End");
}
}
Here is the client code:
public static void main(String[] args) throws IOException {
if ((args.length != 2))
throw new IllegalArgumentException("Parameter(s): <Server> <Port>");
Socket socket = new Socket(args[0], Integer.parseInt(args[1]));
Scanner sc = new Scanner(System.in);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
PrintWriter pw = new PrintWriter(out, true);
while(true) {
String msg="", received="";
String length;
msg = sc.nextLine();
pw.println(msg);
if(msg.equals("END")) break;
if(poraka.equals("Hello")) {
System.out.println();
length = reader.readLine();
for(int i=0;i<Integer.parseInt(length);i++) {
received = reader.readLine();
System.out.println(received);
}
System.out.println("\n"+reader.readLine());
}
else if(msg.contains("FileDownload")) {
System.out.println("FileDownload-Start");
pw.println(msg);
byte[] b=new byte[1024];
File file=new File(reader.readLine().trim());
System.out.println(file.getName().trim());
FileOutputStream fo=new FileOutputStream("D:\\Eclipse WorkSpace\\proekt\\src\\client\\"+file.getName().trim());
System.out.println("file: "+file.getName().trim());
in.read(b,0,b.length);
fo.write(b,0,b.length);
System.out.println("FileDownload-End");
}
I could not find what's causing this issue, so any help possible would be very highly appreciated!
It is because your client requests the data twice:
msg = sc.nextLine();
pw.println(msg); // <-- this is the first time
and then later
else if(msg.contains("FileDownload")) {
System.out.println("FileDownload-Start");
pw.println(msg); // <-- this is the second time
Related
I have a Raspberry pi 4 with Raspbian installed, and I have a computer with Windows 10 installed.I wrote two functions one send a file and the other one receive the file.
when I run this function that sends a file on the raspberry pi 4:
public static void sendFile(String fileName, String ip)
{
BufferedOutputStream outputStream = null;
PrintWriter writer = null;
BufferedReader reader = null;
FileInputStream filein = null;
File file = new File(fileName);
if (!file.exists())
{
System.out.println(fileName + " does not exist");
return;
}
try
{
Socket socket = new Socket(ip, port);
outputStream = new BufferedOutputStream(socket.getOutputStream());
writer = new PrintWriter(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
filein = new FileInputStream(file);
long fileSize = file.length();
writer.println(fileName); // sending file name
writer.println(fileSize); // sending file size in bytes
writer.flush();
byte[] dataBuffer = new byte[1024];
int numberOfReadBytes = 0; // the number of read bytes for each read() function call
System.out.println("Entering the loop");
for(long i = 0; i < fileSize && numberOfReadBytes > -1;)
{
numberOfReadBytes = filein.read(dataBuffer); // read read() function returns the number of bytes tha has been assigned to the array or -1 if EOF(end of file) is reached
outputStream.write(dataBuffer, 0, numberOfReadBytes); // writing the bytes in dataBuffer from index 0 to index numberOfBytes
i += numberOfReadBytes;
}
outputStream.flush();
System.out.println(fileName + " sent to " + ip);
String status = reader.readLine();
System.out.println("Status: " + status + "\t file save successfully on the other machine.");
}
catch(IOException ioe)
{
System.err.println("Status: 0\n" + ioe.getMessage());
}
finally // closing streams
{
try
{
outputStream.close();
reader.close();
writer.close();
filein.close();
}
catch (IOException ioe)
{
System.err.println("Error closing the connection.");
}
}
}
it stops at this line Socket socket = new Socket(ip, port);
and this is the other function that runs on windows 10
public static void receiveFile()
{
// 1- read the file name
// 2- read the size of the file
// 3- read the file and write it
ServerSocket server = null;
Socket socket = null;
BufferedReader reader = null;
BufferedInputStream inputStream = null;
FileOutputStream fileout = null;
PrintWriter writer = null;
try
{
server = new ServerSocket(9999);
socket = server.accept();
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
inputStream = new BufferedInputStream(socket.getInputStream());
writer = new PrintWriter(socket.getOutputStream());
String fileName = reader.readLine(); // reading file name
long fileSize = Long.parseLong(reader.readLine()); // reading file size
System.out.println(fileSize);
// reading file data and write the data
File file = new File(fileName);
fileout = new FileOutputStream(file);
for (long i = 0; i < fileSize; ++i)
{
fileout.write(inputStream.read());
System.out.println(i);
}
fileout.flush();
fileout.close();
writer.println('1');
System.out.println("Status: 1");
System.out.println(fileName+ " is saved successfully");
}
catch (IOException ioe)
{
System.err.println("Status: 0");
System.err.println(ioe.getMessage());
}
finally
{
try
{
reader.close();
inputStream.close();
}
catch(IOException ioe)
{
System.err.println("Error closing connection\n" + ioe.getMessage());
}
}
}
I think windows 10 firewall blocks connection, but I am not sure.
It turns out it was the firewall blocking connection from the raspberry pi
I'm writing a java-c client-server, where the server is in C and the client is in Java. The socket is reused. I don't know why but the client reads the first response from the socket then loops, it's like the client isn't getting "\n". What am I not getting?
The C server sends the response in the format (length:stringlength:string) etc
import java.io.*;
import java.net.*;
public class client {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Use: java Client server port");
System.exit(1);
}
try{
BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Insert input1: ");
String input1 = fromUser.readLine();
System.out.println("Insert input2: ");
String input2 = fromUser.readLine();
Socket s = new Socket(args[0], Integer.parseInt(args[1]));
//BufferedReader fromServer = new BufferedReader(new InputStreamReader(s.getInputStream(),"UTF-8"));
InputStream is = s.getInputStream();
BufferedWriter toServer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8"));
do {
String message = "(" + input1.getBytes("UTF-8").length + ":" + input1 + input2.getBytes("UTF-8").length + ":" + input2 + ")";
toServer.write(message);
toServer.flush();
/*reading result from server*/
//String buff;
String output = "";
byte[] buffer = new byte[4096];
int read;
while((read = is.read(buffer)) != -1) {
output = new String(buffer, 0, read);
System.out.print(output);
System.out.flush();
};
if(output.charAt(0) != '(' || output.charAt(output.length()-1) != ')'){
System.out.println("error using protocol");
}
if(output.indexOf(':')<0){
System.err.println("error using Canonical S-expression!");
System.exit(2);
}
for(int i=output.indexOf(":")+1;i<output.length()-2;i++){
System.out.print(output.charAt(i));
}
System.out.println();
s.close();
System.out.println("Insert input1: ('end' to exit)");
input1 = fromUser.readLine();
} while(!input1.equals("end"));
}
catch(IOException e){
System.err.println(e.getMessage());
e.printStackTrace();
System.exit(100);
}
}
}
I'm creating File Transfer program that will transfer a file to client. But when I transferred the file, It missing the first letter of every lines. What's wrong with my code?
I'm pretty new at java so I don't know what to do next. I've tried changing byte size but no help. What should I do?
Server.java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
class Server {
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket serverSocket = null;
Scanner scan = new Scanner(System.in);
String fileSend;
System.out.print("Type the path to the file to send >> ");
fileSend = scan.nextLine();
try {
serverSocket = new ServerSocket(5467);
} catch (Exception e) {
System.out.println("Could not bind to port 5467, Maybe address is already is use or you need to run as administrator");
return;
}
System.out.println("Listening on port 5467");
System.out.println("Waiting for the connection...");
while (true) {
File FileSend = null;
Socket socket = serverSocket.accept();
OutputStream out = socket.getOutputStream();
System.out.println("Accepted connection : " + socket);
InputStream in = socket.getInputStream();
DataInputStream dataIn = new DataInputStream(in);
String login = dataIn.readUTF();
String password = dataIn.readUTF();
String result = "You credential is ";
if (login.equals("1c18b5cdef8f9b4c5d6b2ad087265e597d1d4639337b73a04a335103c00ec64b") && password.equals("1c18b5cdef8f9b4c5d6b2ad087265e597d1d4639337b73a04a335103c00ec64b13d0b73358bfa8978dfaaf180565bcfecd3dc0631cda525920865145fb3fa131")) {
result += "correct";
} else {
result += "incorrect";
}
DataOutputStream dataOut = new DataOutputStream(out);
try {
dataOut.writeUTF(result);
} catch (FileNotFoundException e) {
System.out.println("No such file or directory");
}
finally
{
FileSend = new File(fileSend);
byte[] FileByteArray = new byte[(int) FileSend.length()];
try {
fis = new FileInputStream(FileSend);
}
catch (FileNotFoundException e) {
System.out.println("No such file or directory");
return;
}
bis = new BufferedInputStream(fis);
File myFile = new File (fileSend);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = socket.getOutputStream();
System.out.println("Sending " + fileSend + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
}
}
}
}
Client.java
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Client {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
Socket socket = null;
String PlainLogin;
String FileOut;
String PlainPassword;
Scanner scan = new Scanner(System.in);
System.out.print("What is the IP address of the server >> ");
String host = scan.nextLine();
try {
socket = new Socket(host, 5467);
} catch (ConnectException | NullPointerException e) {
System.out.println("Connection Refused, Have you run the server first?");
return;
}
OutputStream out = socket.getOutputStream();
DataOutputStream dataOut = new DataOutputStream(out);
InputStream is = socket.getInputStream();
System.out.println("Connection Established");
System.out.println("Credential Required, Please login");
System.out.print("Type your username >> ");
PlainLogin = scan.next();
System.out.print("Type your password >> ");
PlainPassword = scan.next();
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hashInBytes = md.digest(PlainLogin.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hashInBytes) {
sb.append(String.format("%02x", b));
}
String HashedLogin = sb.toString();
byte[] hashInBytesP = md.digest(PlainPassword.getBytes(StandardCharsets.UTF_8));
for (byte b : hashInBytesP) {
sb.append(String.format("%02x", b));
}
String HashedPassword = sb.toString();
dataOut.writeUTF(HashedLogin);
dataOut.writeUTF(HashedPassword);
InputStream in = socket.getInputStream();
DataInputStream dataIn = new DataInputStream(in);
String str = dataIn.readUTF();
if (str == "Your credential is incorrect") {
System.out.println(str);
return;
} else {
System.out.print("Type any file name you want >> ");
scan.nextLine();
FileOut = scan.nextLine();
OutputStream output = new FileOutputStream(FileOut);
byte[] mybytearray = new byte[1024];
is.read(mybytearray, 0, mybytearray.length);
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
output.write(buffer, 0, bytesRead);
}
output.close();
socket.close();
dataIn.close();
System.out.println("Done");
return;
}
}
}
I expect it to show full text like "Java", but it only show "ava"
File is Serializable, so I would suggest you should simply try to send it directly via ObjectOutputStream / ObjectInputStream.
For example on Server side :
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
...
out.writeObject(yourFileObject);
And on Client :
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
...
File receivedFile = null;
try {
receivedFile = (File) in.readObject();
}
catch (IOException e) {
...
}
I'm not entirely sure why this happens exactly, but you shouldn't be using DataInputStream which "lets an application read primitive Java data types", but an InputStreamReader which "is a bridge from byte streams to character streams".
Also, you can wrap that reader into a BufferedReader which lets you read line by line, and you'll end up with something like
try (BufferedReader reader=new BufferedReader(new InputStreamReader(inStream, UTF8));
PrintWriter writer = new PrintWriter(file)) {
reader.lines().forEach(writer::println);
}
for an upload, or
try (PrintWriter writer = new PrintWriter(outStream)) {
Files.lines().forEach(writer::println);
}
for download.
I need to code some proxy server for an assignment in my university. It should be able to display the content of some simple web page given by our professor.
Additionally it should filter the URL and the URL content, and block the web page if one of these contain one of the words in my "bad" array.
My question is, how can I perform this filtering in Java.
Code:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ProxyServer{
//Crate the Port the user wants the proxy to be on
static Scanner sc = new Scanner(System.in);
public static final int portNumber = sc.nextInt();
public static void main(String[] args) {
ProxyServer proxyServer = new ProxyServer();
proxyServer.start();
}
public void start() {
System.out.println("Starting the SimpleProxyServer ...");
try {
String bad[]= new String[4];
bad[0]= "Spongebob";
bad[1]= "Britney Spears";
bad[2]= "Norrköping";
bad[3]= "Paris Hilton";
ServerSocket serverSocket = new ServerSocket(ProxyServer.portNumber);
System.out.println(serverSocket);
byte[] buffer= new byte [1000000] ;
while (true) {
Socket clientSocket = serverSocket.accept();
InputStream inputstream = clientSocket.getInputStream();
System.out.println(" DAS PASSIERT VOR DEM BROWSER REQUEST:");
int n = inputstream.read(buffer);
String browserRequest = new String(buffer,0,n);
System.out.println("Das ist der Browserrequest: "+browserRequest);
System.out.println("Das ist der Erste Abschnitt");
int start = browserRequest.indexOf("Host: ") + 6;
int end = browserRequest.indexOf('\n', start);
String host = browserRequest.substring(start, end - 1);
System.out.println("Connecting to host " + host);
Socket hostSocket = new Socket(host, 80); //I can change the host over here
OutputStream HostOutputStream = hostSocket.getOutputStream();
PrintWriter writer= new PrintWriter (HostOutputStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream));
String Input= null;
while (((Input= reader.readLine())!= null)){
writer.write(Input);
writer.flush();
System.out.println("Empfangen vom Client: "+Input);
}
// for (int i=0; i<4;i++){
// if (inString.contains(bad[i])){
// System.out.println("Bye Idiot");
// break;
// }
// }
System.out.println("Forwarding request to server");
HostOutputStream.write(buffer, 0, n);// but then the buffer that is fetched from the client remains same
HostOutputStream.flush();
InputStream HostInputstream = hostSocket.getInputStream();
OutputStream ClientGetOutput = clientSocket.getOutputStream();
System.out.println("Forwarding request from server");
do {
n = HostInputstream.read(buffer);
String inhalt= HostInputstream.toString();
System.out.println("das ist der inhalt vom HOST: "+ inhalt);
String vomHost = new String(buffer,0,n);
System.out.println("Vom Host\n\n"+vomHost);
// for(int i=0;i<n;i++){
// System.out.print(buffer[i]);
// }
System.out.println("Receiving " + n + " bytes");
if (n > 0) {
ClientGetOutput.write(buffer, 0, n);
}
} while (HostInputstream.read(buffer)!= -1);//n>0
ClientGetOutput.flush();
hostSocket.close();
clientSocket.close();
System.out.println("End of communication");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hi i have a problem with my server, everytime i call "dload" the file gets downloaded but i can't use the other commands i have because they get returned as null. Anyone who can see the problem in the code?
Server :
public class TCPServer {
public static void main(String[] args) {
ServerSocket server = null;
Socket client;
// Default port number we are going to use
int portnumber = 1234;
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
// Create Server side socket
try {
server = new ServerSocket(portnumber);
} catch (IOException ie) {
System.out.println("Cannot open socket." + ie);
System.exit(1);
}
System.out.println("ServerSocket is created " + server);
// Wait for the data from the client and reply
boolean isConnected = true;
try {
// Listens for a connection to be made to
// this socket and accepts it. The method blocks until
// a connection is made
System.out.println("Waiting for connect request...");
client = server.accept();
System.out.println("Connect request is accepted...");
String clientHost = client.getInetAddress().getHostAddress();
int clientPort = client.getPort();
System.out.println("Client host = " + clientHost
+ " Client port = " + clientPort);
// Read data from the client
while (isConnected == true) {
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
clientIn));
String msgFromClient = br.readLine();
System.out.println("Message received from client = "
+ msgFromClient);
// Send response to the client
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("sum")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Double[] list;
list = new Double[5];
String value;
int i;
try {
for (i = 0; i < 5; i++) {
pw.println("Input number in arrayslot: " + i);
value = br.readLine();
double DoubleValue = Double.parseDouble(value);
list[i] = DoubleValue;
}
if (i == 5) {
Double sum = 0.0;
for (int k = 0; k < 5; k++) {
sum = sum + list[k];
}
pw.println("Sum of array is " + sum);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("max")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Double[] list;
list = new Double[5];
String value;
int i;
try {
for (i = 0; i < 5; i++) {
pw.println("Input number in arrayslot: " + i);
value = br.readLine();
double DoubleValue = Double.parseDouble(value);
list[i] = DoubleValue;
}
if (i == 5) {
Arrays.sort(list);
pw.println("Max integer in array is " + list[4]);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("time")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Calendar calendar = GregorianCalendar.getInstance();
String ansMsg = "Time is:, "
+ calendar.get(Calendar.HOUR_OF_DAY) + ":"
+ calendar.get(Calendar.MINUTE);
pw.println(ansMsg);
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("date")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Calendar calendar = GregorianCalendar.getInstance();
String ansMsg = "Date is: " + calendar.get(Calendar.DATE)
+ "/" + calendar.get(Calendar.MONTH) + "/"
+ calendar.get(Calendar.YEAR);
;
pw.println(ansMsg);
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("c2f")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
String celciusValue;
boolean ifRead = false;
try {
pw.println("Input celcius value");
celciusValue = br.readLine();
ifRead = true;
if (ifRead == true) {
double celcius = Double.parseDouble(celciusValue);
celcius = celcius * 9 / 5 + 32;
pw.println(celcius);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("dload")) {
OutputStream outToClient = client.getOutputStream();
if (outToClient != null) {
File myFile = new File("C:\\ftp\\pic.png");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0,
mybytearray.length);
outToClient.flush();
outToClient.close();
bis.close();
fis.close();
} catch (IOException ex) {
// Do exception handling
}
System.out.println("test");
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("quit")) {
client.close();
break;
}
// if (msgFromClient != null
// && !msgFromClient.equalsIgnoreCase("bye")) {
// OutputStream clientOut = client.getOutputStream();
// PrintWriter pw = new PrintWriter(clientOut, true);
// String ansMsg = "Hello, " + msgFromClient;
// pw.println(ansMsg);
// }
// Close sockets
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("bye")) {
server.close();
client.close();
break;
}
msgFromClient = null;
}
} catch (IOException ie) {
}
}
}
Client:
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String args[]) {
boolean isConnected = true;
Socket client = null;
int portnumber = 1234; // Default port number we are going to use
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
try {
String msg = "";
// Create a client socket
client = new Socket("127.0.0.1", 1234);
System.out.println("Client socket is created " + client);
// Create an output stream of the client socket
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
// Create an input stream of the client socket
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
clientIn));
// Create BufferedReader for a standard input
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
System.in));
while (isConnected == true) {
System.out
.println("Commands: \n1. TIME\n2. DATE\n3. C2F\n4. MAX\n5. SUM\n6. DLOAD\n7. QUIT");
// Read data from standard input device and write it
// to the output stream of the client socket.
msg = stdIn.readLine().trim();
pw.println(msg);
// Read data from the input stream of the client socket.
if (msg.equalsIgnoreCase("dload")) {
byte[] aByte = new byte[1];
int bytesRead;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (clientIn != null) {
try {
FileOutputStream fos = new FileOutputStream("C:\\ftp\\pic.png");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = clientIn.read(aByte, 0, aByte.length);
do {
baos.write(aByte, 0, bytesRead);
bytesRead = clientIn.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
System.out.println("File is successfully downloaded to your selected directory"+ "\n" +"*-----------------*"+ "\n" );
} catch (IOException ex) {
System.out.println("Couldn't dowload the selected file, ERROR CODE "+ex);
}
}
}else{
System.out.println("Message returned from the server = "
+ br.readLine());
}
if (msg.equalsIgnoreCase("bye")) {
pw.close();
br.close();
break;
}
}
} catch (Exception e) {
}
}
}
debugged your code and have two hints:
1)
don't surpress your exceptions. handle them! first step would to print your stacktrace and this question on SO wouldn't ever be opened ;-) debug your code!
2)
outToClient.flush();
outToClient.close(); //is closing the socket implicitly
bis.close();
fis.close();
so in your second call the socket on server-side will already be closed.
first thing:
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
This can throw a NumberFormatException, and because args[0] is passed by the user you should handle this.
reading the code also this gave me a problem:
double DoubleValue = Double.parseDouble(value); // LINE 104
Throwing a NumberFormatException when I give c2f as command to the server. You definitively need to handle this exception anywhere in your code and give proper answer to the client, something like:
try{
double DoubleValue = Double.parseDouble(value);
}catch(NumberFormatException e){
// TELL THE CLIENT "ops, the number you inserted is not a valid double numer
}
(in short example, starting from this you have to enlarge the code)
while (isConnected == true) {
I cannot see it! why not use this?
while (isConnected) {
if (msgFromClient != null && msgFromClient.equalsIgnoreCase("sum")){
can be:
if("sum".equalsIgnoreCase(msgFromClient)){
in this case you have no problem with the NullPointerException. (if msgFromClient is null the statement is false).
By the way, date and time command are working fine for me. Check the others.
To fix dload i think you have to delete the line:
outToClient.close();
(EDIT: sorry to maxhax for the same answr, didn't see your answer while writing this)