A Client/Server web application

  • (2 Pages)
  • +
  • 1
  • 2

26 Replies - 3146 Views - Last Post: 28 February 2012 - 08:57 AM Rate Topic: -----

#1 tnecniv  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 109
  • Joined: 03-October 09

A Client/Server web application

Posted 27 February 2012 - 05:36 AM

Hi i am trying to implement a web applcation whereby client can request a filelist from the server containing a list of file available on the server.

I m running into some problem to send the request message as the server doesn't recognize my request message. Please advise which part did i made a mistake.

Thank You

Server:
package MyAssignServer;

import java.io.*;
import java.net.*;
import java.util.*;



public class MyAssignServer {
	public static void main(String args[]) throws Exception {
		//Initializations
		ServerSocket welcomeSocket;
		Socket connectionSocket;
		DataOutputStream outToClient;
		BufferedReader inFromUser;
		BufferedReader inFromClient;
		File myFile;
		FileInputStream inputFile;
		BufferedInputStream buffFile;
		String requestMsg;
		int portNumber;
		int numOfBytes=0;
		String clientRequest;
		String capitalizedSentence;
		int i=1000;
		
		//Server configure port
		inFromUser = new BufferedReader(new InputStreamReader(System.in));
		portNumber =Integer.parseInt(inFromUser.readLine());
		System.out.println("Server receive port number: "+ portNumber);
		
		welcomeSocket = new ServerSocket(portNumber); //creates a server socket named serverSocket listening to port number
		
		while(true){

			//Server Setup Connection request
			connectionSocket = welcomeSocket.accept(); // listen for connections
			
			//Data Transmission IO stream
			inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
			outToClient = new DataOutputStream(connectionSocket.getOutputStream());
			
			//Client request
			clientRequest = inFromClient.readLine();
			System.out.println("Server received the message "+ clientRequest);
			
		    //send numOfBytes to client 
        	myFile = new File("filelist.txt");
            numOfBytes = (int) myFile.length();
            System.out.println("Server: File Size: "+ numOfBytes);
            
			if(clientRequest == "Request"){
	            outToClient.writeBytes(""+numOfBytes+'\n');
	            System.out.println("Server: file size is send out to client");
			}
			else{
				outToClient.writeBytes("unable to send file size"+'\n');
	            System.out.println("Server: not able to send out the file size "+ numOfBytes);
			}
		}
	}
}


package MyAssignClient;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

import javax.swing.*;
import java.net.*;

public class MyAssignClient {
	public static void main(String argv[]) throws Exception
    {
		//Initialization
		Socket clientSocket;
		DataOutputStream outToServer;
		BufferedReader inFromUser;
		BufferedReader inFromServer;
		String fileSize;
		String request;
		while(true){
		//client configure port
		inFromUser = new BufferedReader(new InputStreamReader(System.in)); //take in the server port #
		clientSocket = new Socket("SERVER IP",SERVER PORT #);
		
		//create IO stream
		outToServer = new DataOutputStream(clientSocket.getOutputStream());
		inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
		
		//To Server
		request = inFromUser.readLine();
		System.out.println("Client: My Request message is " + request );
		outToServer.writeBytes(request+ '\n'); //\n indicate end of sentence to server.
		System.out.println("Client: I have send the Req message out! Awaiting your reply...");
		//From Server
		fileSize = inFromServer.readLine();
		System.out.println("Client: Server replied with " + fileSize );
		
		//Display on screen
		System.out.println("Client: File Size: "+fileSize);
		clientSocket.close();
	
		}
    }
	

}



Somehow i think is my server reading the message wrongly but im not sure where and why.

Thank you if there is some guidance.

Is This A Good Question/Topic? 0
  • +

Replies To: A Client/Server web application

#2 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2814
  • View blog
  • Posts: 11,913
  • Joined: 20-September 08

Re: A Client/Server web application

Posted 27 February 2012 - 06:06 AM

Please post the output
Was This Post Helpful? 0
  • +
  • -

#3 guido-granobles  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 171
  • View blog
  • Posts: 617
  • Joined: 02-December 09

Re: A Client/Server web application

Posted 27 February 2012 - 06:13 AM

In the line number 52 class MyAssignServer
 if(clientRequest == "Request"){


You shouldn't compare two Strings using the operator ==, you should use the method equals:
 if(clientRequest.equals("Request")){


In the class MyAssignClient line number 29
 clientSocket = new Socket("SERVER IP",SERVER PORT #);


Where are the ip and the port:
//example
clientSocket = new Socket("10.10.10.1", 3050);


Was This Post Helpful? 1
  • +
  • -

#4 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2814
  • View blog
  • Posts: 11,913
  • Joined: 20-September 08

Re: A Client/Server web application

Posted 27 February 2012 - 06:15 AM

There really is no point in saying 'my app doesn't run properly' if you post code that can't be run AT ALL
Was This Post Helpful? 0
  • +
  • -

#5 tnecniv  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 109
  • Joined: 03-October 09

Re: A Client/Server web application

Posted 27 February 2012 - 06:20 AM

View Postguido-granobles, on 27 February 2012 - 06:13 AM, said:

In the line number 52 class MyAssignServer
 if(clientRequest == "Request"){


You shouldn't compare two Strings using the operator ==, you should use the method equals:
 if(clientRequest.equals("Request")){



Thank You. this solved my problem.
Was This Post Helpful? 0
  • +
  • -

#6 tnecniv  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 109
  • Joined: 03-October 09

Re: A Client/Server web application

Posted 27 February 2012 - 06:25 AM

How can i send and receive a txt file? is this method correct?

	        //send the filelist
			
	        inFile = new FileInputStream(myFile); //Attach a stream to the file
	        byte [] fileInBytes = new byte[numOfBytes]; //Array of bytes
	        inFile.read(fileInBytes);//Read from stream to byte array (need to convert to bytes because output stream can only accept by bytes)
	        outToClient.write(fileInBytes, 0, numOfBytes);
	        System.out.println("Server: sucessfully send out file");




However, i am not sure how the client side can get the file and also save in a specific location.


Please advise

Thank You
Full Server code
package MyAssignServer;

//import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.util.*;

//import javax.imageio.ImageIO;



public class MyAssignServer {
	public static void main(String args[]) throws Exception {
		//Initializations
		ServerSocket welcomeSocket;
		Socket connectionSocket;
		DataOutputStream outToClient;
		BufferedReader inFromUser;
		BufferedReader inFromClient;
		File myFile;
		FileInputStream inputFile;
		BufferedInputStream buffFile;
		String requestMsg;
		int portNumber;
		int numOfBytes=0;
		String clientRequest;
		FileInputStream inFile;
		//BufferedImage img = null;
		
		//Server configure port
		inFromUser = new BufferedReader(new InputStreamReader(System.in));
		portNumber =Integer.parseInt(inFromUser.readLine());
		System.out.println("Server receive port number: "+ portNumber);
		
		welcomeSocket = new ServerSocket(portNumber); //creates a server socket named serverSocket listening to port number
		
		while(true){

			//Server Setup Connection request
			connectionSocket = welcomeSocket.accept(); // listen for connections
			
			//Data Transmission IO stream
			inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
			outToClient = new DataOutputStream(connectionSocket.getOutputStream());
			
			//Client request
			clientRequest = inFromClient.readLine();
			System.out.println("Server received the message "+ clientRequest);
			/*
        	capitalizedSentence = clientRequest.toUpperCase() + '\n';	
            //write out line to socket
        	outToClient.writeBytes(capitalizedSentence);
			*/
			
		    //send numOfBytes to client 
        	myFile = new File("filelist.txt");
            numOfBytes = (int) myFile.length();
       
            System.out.println("Server: File Size: "+ numOfBytes);
            
			if(clientRequest.equals( "Request")){
	            outToClient.writeBytes(""+numOfBytes+'\n');
	            System.out.println("Server: file size is send out to client");
			}
			else{
				outToClient.writeBytes("unable to send file size"+'\n');
	            System.out.println("Server: not able to send out the file size ");
			}  
	        //send the filelist
			
	        inFile = new FileInputStream(myFile); //Attach a stream to the file
	        byte [] fileInBytes = new byte[numOfBytes]; //Array of bytes
	        inFile.read(fileInBytes);//Read from stream to byte array (need to convert to bytes because output stream can only accept by bytes)
	        outToClient.write(fileInBytes, 0, numOfBytes);
	        System.out.println("Server: sucessfully send out file");
		}
	}
}




Was This Post Helpful? 0
  • +
  • -

#7 guido-granobles  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 171
  • View blog
  • Posts: 617
  • Joined: 02-December 09

Re: A Client/Server web application

Posted 27 February 2012 - 07:05 AM

A better way would be:
//Sending a file.
FileInputStream fis = null;
try {

	fis = new FileInputStream(pathName);
	byte[] buf = new byte[4 * 1024]; // 4K buffer
	int bytesRead;
	while ((bytesRead = fis.read(buf)) != -1) {
			out.write(buf, 0, bytesRead);
	}
} catch (FileNotFoundException e) {
	out.println("File not found: " + pathName);
} catch (IOException e) {
	out.println("IO error sending a file " + pathName + ": "
		+ e.getMessage());
} finally {
	if (fis != null)
		fis.close();
}
		
.
.
.
.

//Reading and writing a file		
out = new BufferedOutputStream(new FileOutputStream(dirTemp));
.
.
.
		
in = conn.getInputStream();
byte[] buffer = new byte[1024];
int numRead;
long numWritten = 0;
while ((numRead = in.read(buffer)) != -1) {
		out.write(buffer, 0, numRead);
		numWritten += numRead;
}


Was This Post Helpful? 1
  • +
  • -

#8 tnecniv  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 109
  • Joined: 03-October 09

Re: A Client/Server web application

Posted 27 February 2012 - 08:04 AM

View Postguido-granobles, on 27 February 2012 - 07:05 AM, said:

A better way would be:
//Sending a file.
FileInputStream fis = null;
try {

	fis = new FileInputStream(pathName);
	byte[] buf = new byte[4 * 1024]; // 4K buffer
	int bytesRead;
	while ((bytesRead = fis.read(buf)) != -1) {
			out.write(buf, 0, bytesRead);
	}
} catch (FileNotFoundException e) {
	out.println("File not found: " + pathName);
} catch (IOException e) {
	out.println("IO error sending a file " + pathName + ": "
		+ e.getMessage());
} finally {
	if (fis != null)
		fis.close();
}
		
.
.
.
.

//Reading and writing a file		
out = new BufferedOutputStream(new FileOutputStream(dirTemp));
.
.
.
		
in = conn.getInputStream();
byte[] buffer = new byte[1024];
int numRead;
long numWritten = 0;
while ((numRead = in.read(buffer)) != -1) {
		out.write(buffer, 0, numRead);
		numWritten += numRead;
}




May i know which part of this code can i declare a directory where the file is to be store?
does it work for sending jpeg,gif or bmp file?

for your advise.

thank u
Was This Post Helpful? 0
  • +
  • -

#9 guido-granobles  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 171
  • View blog
  • Posts: 617
  • Joined: 02-December 09

Re: A Client/Server web application

Posted 27 February 2012 - 08:18 AM

The varibles pathName and dirTemp contain the path (directory) where the file is going to be read and stored and yes it can send any binary file.
Was This Post Helpful? 0
  • +
  • -

#10 tnecniv  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 109
  • Joined: 03-October 09

Re: A Client/Server web application

Posted 28 February 2012 - 02:46 AM

View Postguido-granobles, on 27 February 2012 - 08:18 AM, said:

The varibles pathName and dirTemp contain the path (directory) where the file is going to be read and stored and yes it can send any binary file.


May i know what datatype to declare for variable in and out for the client ?
and also what is the directory format?
Was This Post Helpful? 0
  • +
  • -

#11 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2814
  • View blog
  • Posts: 11,913
  • Joined: 20-September 08

Re: A Client/Server web application

Posted 28 February 2012 - 03:31 AM

http://technojeeves....copying-streams
Was This Post Helpful? 0
  • +
  • -

#12 tnecniv  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 109
  • Joined: 03-October 09

Re: A Client/Server web application

Posted 28 February 2012 - 04:52 AM

I manage to get the data send out by the server after the client has entered Request.
May i know where can i adjust my code so that it will be store in my directory namely a folder call ReceivedFiles inside the workspace of my client?

server:
package MyAssignServer;

//import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.util.*;

//import javax.imageio.ImageIO;



public class MyAssignServer {
	public static void main(String args[]) throws Exception {
		//Initializations
		ServerSocket welcomeSocket;
		Socket connectionSocket;
		DataOutputStream outToClient;
		BufferedReader inFromUser;
		BufferedReader inFromClient;
		File myFile;
		FileInputStream inputFile;
		BufferedInputStream buffFile;
		String requestMsg;
		int portNumber;
		int numOfBytes=0;
		String clientRequest;
		FileInputStream fis = null;
		
		
		//Server configure port
		System.out.println("Please enter the port number...");
		inFromUser = new BufferedReader(new InputStreamReader(System.in));
		portNumber =Integer.parseInt(inFromUser.readLine());
		System.out.println("Server receive port number: "+ portNumber);
		String pathName= " ";
		
		welcomeSocket = new ServerSocket(portNumber); //creates a server socket named serverSocket listening to port number
		
		while(true){

			//Server Setup Connection request
			connectionSocket = welcomeSocket.accept(); // listen for connections
			
			//Data Transmission IO stream
			inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
			outToClient = new DataOutputStream(connectionSocket.getOutputStream());
			
			//Client request
			
			clientRequest = inFromClient.readLine();
			System.out.println("Server received the message "+ clientRequest);
			
			//send the filelist
        	myFile = new File("filelist.txt");
            numOfBytes = (int) myFile.length();
       
            System.out.println("Server: File Size in int: "+ numOfBytes);
            
			if(clientRequest.equals( "Request")){
	            //outToClient.writeBytes(""+numOfBytes+'\n');
	            System.out.println("Server: Request is the same as"+ clientRequest);
				try{
					fis = new FileInputStream(pathName);
					byte[] buf = new byte[4*1024]; //4k buffer size
					int bytesRead;
					while ((bytesRead = fis.read(buf)) !=-1){
						outToClient.write(buf, 0, bytesRead);
					}
					System.out.println("Server: File Size in bytes: "+ buf);
				}
				catch(FileNotFoundException e){
					outToClient.writeBytes("File not found" + pathName);
				}
				catch(IOException e){
					outToClient.writeBytes("IO error sending a file "+ pathName + ": " + e.getMessage());
				}
				finally{
					if(fis !=null){
						fis.close();
					}
				}
			}
			else
				System.out.println("Server: Request is not "+ clientRequest);
		}
	}
			
}




Client:

package MyAssignClient;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

import javax.swing.*;
import java.net.*;

public class MyAssignClient {
	public static void main(String argv[]) throws Exception
    {
		//Initialization
		Socket clientSocket;
		DataOutputStream outToServer;
		BufferedReader inFromUser;
		BufferedReader inFromServer;
		String fileSize;
		String request;
		
		String ipAddress= "172.17.47.185";//temp hardcoded
		int portNumber = 6789; //temp hardcorded
		
		long numWritten = 0;
		InputStream in;
		BufferedOutputStream out;
		
		
		//client configure port
		System.out.println("please enter server's IP address");
		inFromUser = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Client received IP address"+ ipAddress);
		
		System.out.println("Please enter the port number");
//		inFromUser = new BufferedReader(new InputStreamReader(System.in));
//		portNumber =Integer.parseInt(inFromUser.readLine());
		System.out.println("Client received port number: "+ portNumber);
		
		
		while(true){		
			//client setup connection
			inFromUser = new BufferedReader(new InputStreamReader(System.in)); //take in the server port #
			clientSocket = new Socket(ipAddress,portNumber);
			
			//create IO stream
			outToServer = new DataOutputStream(clientSocket.getOutputStream());
			inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			
			//To Server
			System.out.println("Client: Enter the command...");
			request = inFromUser.readLine();
			System.out.println("Client: My Request message is " + request );
			outToServer.writeBytes(request+ '\n'); //\n indicate end of sentence to server.
			System.out.println("Client: I have send the Req message out! Awaiting your reply...");
			
			//From Server
			//fileSize = inFromServer.readLine();
			//System.out.println("Client: Server replied with " + fileSize );
			
			out = new BufferedOutputStream(new FileOutputStream("filelist.txt"));
			in = clientSocket.getInputStream();
			System.out.println("Server send the file"+ in);

			byte[] buffer = new byte[1024];
			int numRead;
			while ((numRead = in.read(buffer)) != -1) {
					out.write(buffer, 0, numRead);
					numWritten += numRead;
			}
			System.out.println("Client: job done");

	
		}
    }
}




This is what my console shows me after i run the above server/client:

Server
Please enter the port number...
6789
Server receive port number: 6789
Server received the message Request
Server: File Size in int: 160
Server: Request is the same asRequest





Client
please enter server's IP address
Client received IP address172.17.47.185
Please enter the port number
Client received port number: 6789
Client: Enter the command...
Request
Client: My Request message is Request
Client: I have send the Req message out! Awaiting your reply...
Server send the filejava.net.SocketInputStream@1b17a8bd





Please advise. Sorry for the poor coding. This is the first time i trying Java.


Thank You.
Was This Post Helpful? 0
  • +
  • -

#13 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2814
  • View blog
  • Posts: 11,913
  • Joined: 20-September 08

Re: A Client/Server web application

Posted 28 February 2012 - 05:41 AM

What version of Java are you using?
Was This Post Helpful? 0
  • +
  • -

#14 tnecniv  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 109
  • Joined: 03-October 09

Re: A Client/Server web application

Posted 28 February 2012 - 06:38 AM

View Postg00se, on 28 February 2012 - 05:41 AM, said:

What version of Java are you using?


sorry im new. im not sure about the version you referring to. Please advise. Thank you
Was This Post Helpful? 0
  • +
  • -

#15 guido-granobles  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 171
  • View blog
  • Posts: 617
  • Joined: 02-December 09

Re: A Client/Server web application

Posted 28 February 2012 - 06:41 AM

In the class MyAssignServer line 63:
fis = new FileInputStream(pathName);


I can't see where you declared the variable pathName. It should pointing to the file that will be sent.

In the client:
out = new BufferedOutputStream(new FileOutputStream("filelist.txt"));

[s]in = clientSocket.getInputStream();[/s]

System.out.println("Server send the file"+ in);

byte[] buffer = new byte[1024];
int numRead;

while ((numRead = inFromUser.read(buffer)) != -1) {
   out.write(buffer, 0, numRead);
}



inFromUser is the object that you should be use in order to read the response.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2