Hello :)

I am creating a simple client/server file sharing application which I run on same computer. Mine. :) I wish to make the client be able to get a certain file by letting user type "get filename" in the console. When they do, and the server responds, the server checks if there is such a file and sends to the user. While I got the basics working - like being able to send/recieve primitive types - I still have trouble actually sending a file. And letting the client have the command "get filename". Could someone assisst please?

Best Wishes

Here's my coding:
http://pastebin.com/Spfp6XFC

I still have trouble actually sending a file

Can you explain in more detail what the problem is?
Here are two compiler problems I got when I tried to compile your program.

SimpleServer.java:67: cannot find symbol
symbol : constructor BufferedReader(int)
location: class java.io.BufferedReader
BufferedReader bfr = new BufferedReader(inputFromClient.read(buffer));
^
SimpleServer.java:82: cannot find symbol
symbol : variable outToClient
location: class SimpleServer
outToClient.write(buf, 0, len);
^

1)Can you explain why you're putting the read() method in the Constructor for BufferedReader?
What does read() return?
2) where is outToClient defined?

Please compile your code before posting it and fix these typo errors!!

Edited 6 Years Ago by NormR1: n/a

Can you explain in more detail what the problem is?
Here are two compiler problems I got when I tried to compile your program.

1)Can you explain why you're putting the read() method in the Constructor for BufferedReader?
What does read() return?
2) where is outToClient defined?

Please compile your code before posting it and fix these typo errors!!

Sorry. My bad. Here is the code, which I "cleaned" up.
I used read() because I don't fully understand BufferedReader.
As far as I get it, it returns int value of the character it encounters.
I forgot to add "put" in the outToClient. outputToClient should it be. :)

The problem is, that no file with the name of user input is ever sent to client.
And once the the user writes an input - the client seemingly does nothing. And nothing is sent to client from the server.

Server side:
http://pastebin.com/K2jn8bUt

Client side:
http://pastebin.com/3rHSi7vJ

I don't fully understand

If you read the API doc it tells you what type the Constructor takes. What does it want?
read() returns an int, so that obviously is wrong.

problem is, that no file with the name of user input is ever sent to client

How is this supposed to happen? How does the server get the name of the file to send?

If you read the API doc it tells you what type the Constructor takes. What does it want?
read() returns an int, so that obviously is wrong.

How is this supposed to happen? How does the server get the name of the file to send?

Yes, true. I don't always understand what they are actually meaning in the API however. That's the trick. Sure, constructors and all and their reutrn types is shown - which makes it a little easier. But when learning about what things do, as the case with read() method, I don't understand always. In the case for read(), it returns an int - but is said to read characters? The best way I interpreted that information is that it returns the int value of that char which is read.


As for the file sending - I have thought this way:
First, the input and output streams are created so that information can be send/recieved.
Then they are tried to be created. When accomplished, the user should write the filename with the Scanner object. That value is then stored in a string "filename". Then, that value is passed to the server (line 56 in SimpleClient class) and the output is flushed.
The "filename" value from client is used as input on the server side (line 58 in SimpleServer class) and in that way is passed as a string value for "filename" in server class. Then, if that file exists in the server side (line 68 SimpleServer class), it is written in the output - and in that way sent to the client. But... it seems like I haven't written a code to actually write a file... doesn't seem like anything will be written either. At least - that's my observation. Do you have an advice?

Your explanation of what you want to do is good and makes sense.
So do the steps one at a time. Try to get these steps done first.
Are you able to get the name of the file from the user?
Are you able to send that name to the server?
Does the server read that name correctly?

Your explanation of what you want to do is good and makes sense.
So do the steps one at a time. Try to get these steps done first.
Are you able to get the name of the file from the user?
Are you able to send that name to the server?
Does the server read that name correctly?

I've just been checking through it over and over and over again.
And it doesn't seem like it's something from the server side. Franquely,
I believe it is the client part that doesn't send proper information.
Most notably, on line 56. It is supposed to write a sequence of chars and send it to
the server part. And in the server part, I have the code that should do the job right:

BufferedReader bfr = new BufferedReader(new InputStreamReader(inputFromClient));

But wouldn't this code be "translating" the input stream correctly from the client? Sheesh - all these streams, inputs and outputs make me go nuts!

I've made some debugging changes to your code and do not have a solution yet. Here are your programs with an old one of mine.

Edited 6 Years Ago by NormR1: n/a

Attachments
/*	posted Today 17:07      
Profile for Simon Evans   Email Simon Evans   
Dear Programmers,

I am currently experiencing difficulty with a Client side program, which runs in response to a
Server program, or at least would, if I could get it in order. The difficulty stems from the fact
that I can't subclsss (extend) it from the Jframe and Thread class using extends JFrame, Thread
as the compiler doesn't like it, so I had the notion of putting the main method in an instantiating
program, and declaring that to extend Thread and have the Client class extend JFrame. 
The problem
is that the Client program has an ActionListener/Performed method - which will call another 
method(sendMessage()) within Client program - it must be called from within the Action method - but
without the object of class Client it can't call the sendMessage(), and with the Client Object being
declared within the ActionListener method - it will just keep recreating the clsss Client - upon the
ActionListener being activated ie: pressing the 'SEND' button keeps recreating another ClientGUI, 
complete with 'SEND' button, for the undending pressing of. Anyhow I'll put the code below,as it 
can tell it better than I can, Clsss Server runs okay, but without ClientGUI its obselete. 
ClientGUI creates the GUI but without the ActionPerformed method it is a non-starter.
*/
//***************************************************************************
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.awt.Window.*;
import java.awt.Label;

public class ClientServerTest { // extends Thread {

   //*********************************************
   // Starts here 
   public static void main(String args[]){
      Server.main(new String[]{});  // start the server
      final ClientGUI cGUI = new ClientGUI();

      Runtime.getRuntime().addShutdownHook(new Thread(){
//         @Override
         public void run() {           // NOT called???
            System.out.println("Shutting down");
            cGUI.shutdown();
         }
      });
   } // end main()
} // end class ClientServerTest

//**************************************************************************
class ClientGUI extends JFrame  {
   Socket socket;
   BufferedReader in;
   PrintStream out;
   String host;
   int port = 1234;
//   String message;
   private JFrame frame;
   private JTextField TeF = new JTextField(25);
   JTextArea TeA = new JTextArea(20,30);
   JScrollPane scroll = new JScrollPane(TeA);
   JButton b1 = new JButton("SEND");
   String fileName = " ";
   String savedFile = " ";
   JPanel west = new JPanel();
   JPanel east = new JPanel();
   JPanel south = new JPanel();
   MyJButtonListener myJButtonListener;
   final public static String ShutDownMsg = "ShuttingDown";

   private void setupGUI() {
      TeA.setEditable(false);             // output only
      TeA.setBackground(Color.lightGray);
      Container c = getContentPane();
      c.setLayout(new BorderLayout());
      c.add(BorderLayout.EAST,east);
      west.add(scroll);
      c.add(BorderLayout.WEST,west);
      south.add(TeF);
      south.add(b1);
      c.add(BorderLayout.SOUTH,south);
      myJButtonListener = new MyJButtonListener(this);   //<<<<<<<<<<<
      b1.addActionListener(myJButtonListener);
      setSize(400,380);
      setVisible(true);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
   //----------------------------------------
   // Constructor
   ClientGUI(){
      super("Client - Server test");
      setupGUI();
      getConnection();
      receiveMessage();
   }

   public void getConnection() {
      try {
         host = InetAddress.getLocalHost().getHostAddress();
         socket = new Socket(host,port);
         in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         out = new PrintStream(socket.getOutputStream());
//         System.out.println("Client - getConn out=" + out);
      }catch(UnknownHostException e){
         System.out.println("Client - getConnection():" + e);
      }catch(IOException e) {
         System.out.println("Client - getConnection():" + e);
      }
   }
   
   public void sendMessage(String message) {
      message = TeF.getText();
      System.out.println("Client sent:- " + message);
//      System.out.println("out= " + out);
      out.println(message);
   }

   public void receiveMessage() {
      try {
         while (true){
            String message = in.readLine();
            System.out.println("Client Received:" + message);
            TeA.append(message + "\n");
            TeF.setText( ""); // clear input area
            TeF.requestFocus();
         } // end while()
      }catch(IOException e) {
         System.out.println("Client - receiveMessage():" + e);
      }
   }

   public void shutdown() {
      sendMessage(ShutDownMsg);
   }
   //---------------------------------------------
   class MyJButtonListener implements ActionListener{
      ClientGUI clientgui;
      MyJButtonListener(ClientGUI cg) {
         clientgui = cg;    // save
      }
      public void actionPerformed(ActionEvent e){
         if(e.getActionCommand().equals("SEND")) {
//            ClientGUI clientgui = new ClientGUI();
            clientgui.sendMessage(TeF.getText());
         }else{
            System.out.println("unknown ae=" + e);
         }
      }
   }
} // end class ClientGUI

//***************************************************************************
class Server  extends Thread {
   ServerSocket server;
   Socket connection;
   
   BufferedReader in;
   PrintStream out;

   int port = 1234;
//   String message;
   
   public static void main(String args[]) {
      Server server = new Server();
      server.start();
   }

   public void run() {
      getConnection();
      recieveMessage();
   }
   private void getConnection() {
      try    {
         server = new ServerSocket(port);
         System.out.println("Waiting for client...");
         connection = server.accept();
         System.out.println("Server got conection: " + connection);
         in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
         out = new PrintStream(connection.getOutputStream());
      }    catch(IOException e)   {
         System.out.println("Server - getConnection();" + e);
      }
   }
   
   private void recieveMessage() {
      try {
         while(true) {
            String message = in.readLine();
            System.out.println("Server - recMsg msg="   + message);
            sendMessage(message);
         }
      } catch(IOException e) {
         System.out.println("Server -receiveMessage():" + e);
      }
   }
   
   private void sendMessage(String message){
     out.println(message);
   }
} // end class Server

//***************************************************************************

/*As you may know, you have to run the Server program first, then the MainMethod to launch the ClientGUI
program. I think the methods in ClientGUI are coded alright - to put input to text field to input and
output streams and to transfer message thus initialised to the textArea.
Anyway thank you much for your help, particularly as most people out there are preoccupied with loot
before they're prepared to offer any help.
Yours
Simon
*/
/*  >>>> Sample output: <<<<
Waiting for client...
Server got conection: Socket[addr=/127.0.0.1,port=1162,localport=1234]
Client - getConn out=java.io.PrintStream@64c34e
Client sent:- sdsdsdf
out= java.io.PrintStream@64c34e
Server - recMsg msg=sdsdsdf
Client Received:sdsdsdf

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


class SimpleClient {

	static int port = 8000;
	static String host = "localhost";
	static Socket socket;
	
	public static void main(String[] args) {
		
		new SimpleClient(host, port);
		
	}//end of main
	
	
	public SimpleClient(String server, int port) {
		DataInputStream inputFromServer = null;
		DataOutputStream outputToServer = null;
		BufferedReader bfr = null;
		File file = null;
		
		socket = null;
		String filename = null;
		
		try {
			//create a socket to connect to server socket
			socket = new Socket(server, port);
		} catch (java.io.IOException ioe) {
			System.out.println("Couldn't create socket.");
         ioe.printStackTrace();     //java.net.ConnectException: Connection refused: connect
		}//end of trying to create socket
		
		System.out.println("got connection " + socket);
	
		try {
			outputToServer = new DataOutputStream(socket.getOutputStream());
		} catch (java.io.IOException ioe) {
			System.out.println("Couldn't create output stream.");
         ioe.printStackTrace();
		}//end of trying to create output stream	
		

		//Scanner object for reading
//		Scanner sc = new Scanner(System.in);
		filename = "Testfile.txt"; //sc.nextLine();
		
		try {
			outputToServer.writeChars(filename);
         System.out.println("wrote " + filename + ", size=" + outputToServer.size());  // size=24  (12*2)
//			outputToServer.flush();        // ????????????????????????????

		} catch (java.io.IOException ioe) {
			System.out.println("Couldn't write to server.");
         ioe.printStackTrace();
		}//end of trying to write to server
		
		try {	
			//create data input/output streams
			inputFromServer = new DataInputStream(socket.getInputStream());
		} catch(java.io.IOException ioe) {
			System.out.println("Couldn't create input stream.");
         ioe.printStackTrace();
		}//end of trying to create input stream
		
      System.out.println("trying to read from: " +  inputFromServer);
		try {
			bfr = new BufferedReader(new InputStreamReader(inputFromServer));
			String fname = bfr.readLine();
         System.out.println("read fname=" + fname);
			file = new File(fname + "_serverMade.txt");
			file.createNewFile();			
		} catch (java.io.IOException ioe) {
			System.out.println("Couldn't recieve information from server.");
         ioe.printStackTrace();
		}//end of trying to write to server	
	}//end of area client method
	
	

}//end of class
import java.io.*;
import java.net.*;

public class SimpleServer {
	static int port = 8000;
	
	public static void main(String[] args) { 
		new SimpleServer(port);
		
	}//end of main
	
	
	public SimpleServer(int portnr) {
		ServerSocket servsock = null; //<-- won't be found because of try/catch block
		Socket sock = null; //<-- won't be found because of try/catch block
		InputStream inputFromClient = null;
		OutputStream outputToClient = null;
		FileInputStream fis = null;
		InputStreamReader isr = null;
		File file = null;
		String filename = null;
		
		
		try {
			//ServerSocket servsock;
			servsock = new ServerSocket(portnr); //creates new server socket
		} catch (java.io.IOException ioe) {
			System.out.println("Coudln't create a server socket.");
		}//end of trying to create server socket
		
		System.out.println("server waiting for connect on " + servsock);
		try {
			//Socket sock;
			sock = servsock.accept();
		} catch (java.io.IOException ioe) {
			System.out.println("Couldn't listen to socket.");		
		}//end of trying to listen to socket	
		
		
		System.out.println("server got connect on " + sock);
		//create data input/output streams
		try {
			inputFromClient = new DataInputStream(sock.getInputStream());
			
		} catch (java.io.IOException ioe) {
			System.out.println("Couldn't get any input.");
		}//end of trying to get input
		
		
		try {
			outputToClient = new DataOutputStream(sock.getOutputStream());			
		} catch (java.io.IOException ioe) {
			System.out.println("Couldn't write to client.");
		}//end of trying to send 	
		
		System.out.println("waiting for data from client");
		try {
			//Using an InputStreamReader to read the bytes
			BufferedReader bfr = new BufferedReader(new InputStreamReader(inputFromClient));
			filename = bfr.readLine();						
         System.out.println("got filename=" + filename); //got filename= T e s t f i l e . t x t
		} catch (java.io.IOException ioe) {
			System.out.println("Couldn't read bytes from client.");
         ioe.printStackTrace();
		}//end of trying to read bytes from client	
		
		       // WHat is this code supposed to do?
		try {
//			file = new File(filename);
//			if ( file.exists() ) {
				byte[] buf = new byte[1024];
				int len;
				
     		   System.out.println("echoing data from client");
				while ((len = inputFromClient.read(buf)) > 0) {
     		      System.out.println("echoing data from client len=" + len);
					outputToClient.write(buf, 0, len);
				}//end of while
     		   System.out.println("done echoing data from client");
				
				//inputFromClient.close();
				//outputToClient.close();
				
//			}//end of if
//			else {
//				System.out.println("File not found");
//			}
		} catch (java.io.IOException ioe) {
			System.out.println("Couldn't send result to client.");
         ioe.printStackTrace();
		}//end of trying send result to client		
	}//end of area server method
	
	
}//end of class

I don't work with GUIs so I don't understand that code

Which code is that?
Did you try my ClientServerTest.java?
It doesn't have any GUI.

Sorry, it does have GUI. But that's not important
Look at the classes and methods it uses to send/receive data.

can u share ur code with me ? actually developing app for android and very less time ... plz reply as soon as poss

Comments
Two year old thread
This article has been dead for over six months. Start a new discussion instead.