?
Solved

File Server and client

Posted on 2003-03-19
13
Medium Priority
?
236 Views
Last Modified: 2010-03-31
hi all, I have created a servergui class, a server class (funtionalities), and a clientgui class.
As i am using GUI, i did not allow the user to define the directory for the server to serve files.

(clientgui) I have a simple portno. field and ip field allowing clients to connect to the server. I have already taken care of clicking 'connect' with empty inputs by appending to the console the usage message. However, it (the message) doesnt appear.

(server) The server can append " listening for connections " at first, but when a client is connected to it, the message that i append to tell the one at the server that a client has connected to the server does not append as well.

To the more important part, sending and receiving, either messages written by the server to the client ,OR , client sending the filename to the server after typing down the filename and clicking 'download',OR , server sending files to client, doesnt seems to work.

(server)
public void sendFile(String filename) throws Exception
            {
                  file = new File(filename);
            if ((! file.exists()) || file.isDirectory())
            {
                     pw.println("File error,Pls enter a valid file\n");
            }
            else
            {
               pw.println("Success! Reading " + filename + "...\n");
               pw.println("Sending file to " + socket.getInetAddress().getHostName() + " now.\n");
               
               // read lines from file and send to the client
                     BufferedReader input =  new BufferedReader(new FileReader (file));
                     String line;
                     while ((line = input.readLine()) != null)
                     {
                                 pw.println(line);
                     }
            }

            if (pw.checkError())
            {
               throw new Exception("Error while transmitting data.");
            }
         }
         
      
public void run()
{
            pw.println("client running now.\n");

            try
            {
               br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
               pw = new PrintWriter(socket.getOutputStream() );
               String filename = br.readLine();
               
               sendFile(filename);              
            }
            catch (Exception e)
            {
                  pw.println(e.getMessage());      
              }            
           
            finally
            {
               try
               {
                       pw.close();
                       br.close();
                  socket.close();
               }
               catch (IOException e)
               {}
            }
           
            }

my questions are:
1) i use printwriters to write from servers to clients and clients to servers, some msg like to tell the clients they have successfully found the file and ready to receive the file is not appended to the console of the client. how can i correct that?

2) becos client only states the filename, does tat mean the boundary of the files found is the folder which holds these java files?

3) and if so? how isit going to write to the same folder? with the same name?

4) and when i receive input streams for eg from server to client, how can i differentiate whether it a line from the file or it is actually the server msgs? (Note: i did not use File'Input/Output'Streams) Should i use? and how can i append the server msgs to the console of clientgui?

Whats happening to my codes now:
1) the 3 files are compilable.
2) when i connected successfully, no appended server msgs to server console to inform user of connected client.
3) when i try to put in invalid port and ip, no appended error msgs. (however the command prompt will have a list of errors listing out)
4) when i connected properly to the server and typed in test.txt which i have created in the same directory as the java files and then click jbutton donwload, im not sure whether is there sending of the file over to client and im not sure where will it reside. Lastly, after clicking download with a valid txt file, the clientgui just hang there, which i have to ctrl+alt+del to terminate it. What should i do?

I hope can get help from here... since all my frens are also stuck with their own assignment as well..
thanks alot. (hmm, im left with 25 points........ =(  .......... )
0
Comment
Question by:hywm
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 5
13 Comments
 
LVL 4

Expert Comment

by:kokchoon78
ID: 8171147
you have multiple problems on your coding...., i think you need to solve it one by one :

1) ensure your server is listening connection.
2) ensure your client able to connect to your server.
3) ensure your client can allocate the need file to upload to server.
4) ensure your server can reveice the file from client.

post you server code here for solving problem (1).

regards,
Kok Choon.
0
 

Author Comment

by:hywm
ID: 8173723
Erm just a point to note, my application is for client to download txt file from Server. Not vice versa.

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

public class server extends Thread
{
      private File f;
      private int portnum;
      private JTextArea console;
      private Socket socket;
      private ServerSocket server;
      private int noOfCon = 0;
      private DataOutputStream dos;
      private DataInputStream dis;
      
      public server(int portnum, JTextArea console, ServerSocket server)
      {
            this.portnum = portnum;
            this.console = console;
            this.server = server;
      }
      
      public void run()
      {
            try
            {      
                  console.append("Listening for connections on port " + portnum + " ... \n");            
                  while(true)
                  {
                        socket = server.accept();
                        console.append("Received connection from " + socket.getInetAddress().getHostName() + "\n");
                        
                        noOfCon++;
                        console.append("There is / are " + noOfCon + " connection/s  \n");                        
                        ConnectionHandler ch = new ConnectionHandler(socket);
                        
                  }
            }
            catch(Exception e)
            {
                  e.printStackTrace();
                  console.append(e.getMessage());
            }            
      }
      
      
      class ConnectionHandler extends Thread
      {
            private Socket socket;
            private PrintWriter pw;
            private BufferedReader br;
            
            public ConnectionHandler(Socket socket)      
            {
                  this.socket = socket;
                  start();
            }
            
            public void sendFile(String filename) throws Exception
            {
                  f = new File(filename);
                  if ((! f.exists()) || f.isDirectory())
                  {
                        pw.println("File error,Pls enter a valid file\n");
                  }
                  else
                  {
                        pw.println("Success! Reading " + filename + "...\n");
                        pw.println("Sending file to " + socket.getInetAddress().getHostName() + " now.\n");
                        
                        BufferedReader input =  new BufferedReader(new FileReader (f));
                        String line;
                        while ((line = input.readLine()) != null)
                        {
                              pw.println(line);
                        }
                  }
                  
                  if (pw.checkError())
                  {
                        throw new Exception("Error while transmitting data.\n");
                  }
            }
            
            
            public void run()
            {                  
                  try
                  {
// im using datai/ostreams to print the messages on console, but what about file sending? can i use the same stream thruout? disdos or buffered/printwrite?
                        dis = new DataInputStream(socket.getInputStream());
                        dos = new DataOutputStream(socket.getOutputStream());
                        console.append("Got I/O streams.\n");
                        
                        console.append("Sending message \"Connection successful\" \n");
                        dos.writeUTF("Connection successful");
                        console.append("Client message: " + dis.readUTF());
                        
                        // file sending here..
                        String filename = br.readLine();
                        
                        sendFile(filename);              
                  }
                  catch (Exception e)
                  {
                        e.printStackTrace();
                        console.append(e.getMessage() + "\n");      
                  }            
                  
                  finally
                  {
                        try
                        {
// either disdos or pw/br here....
                              pw.close();
                              br.close();
                              socket.close();
                        }
                        catch (IOException e)
                        {}
                  }
                  
            }
      } // end connectionhandler class
      
      
}
0
 

Author Comment

by:hywm
ID: 8173733
my server gui

import java.util.*;
import java.net.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class fserver extends JFrame implements ActionListener
{
     private int portnum;    
     private Socket socket;
     private ServerSocket ss;
     private server s;
     
     // GUI panels. n stands for north s for south and c for centre
     private JPanel mainpanel, npanel, spanel;
     private JTextArea console;
     private JTextField portField;
     // status to display no. of current connection, listen to start waiting for connection
     private JButton listen, status, close;
     private JScrollPane scroll;
     
     public fserver()
     {  
          super("Server");
          //this.server = server;
          //this.socket = socket;
          setSize(600, 350);
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          mainpanel = new JPanel(new BorderLayout());
         
          // gui in north panel
          npanel = new JPanel();
          JLabel pn = new JLabel("Port Number: ");
          portField = new JTextField(8);
          listen = new JButton("Listen");
          listen.addActionListener(this);
          npanel.add(pn);
          npanel.add(portField);
          npanel.add(listen);
         
          //cpanel = new JPanel();
          console = new JTextArea();
          console.setEditable(false);
          scroll = new JScrollPane(console);
          //cpanel.add(console);
         
          spanel = new JPanel();
          status = new JButton("Status");
          status.setEnabled(false);
          close = new JButton("Close");
          close.addActionListener(this);
          spanel.add(status);
          spanel.add(close);
         
          mainpanel.add(npanel, BorderLayout.NORTH);
          mainpanel.add(scroll, BorderLayout.CENTER);
          mainpanel.add(spanel, BorderLayout.SOUTH);
         
          setContentPane(mainpanel);
     }    
     
     public void actionPerformed(ActionEvent e)
     {
          if(e.getSource() == listen)
          {
               try
               {
                    status.setEnabled(true);
                    portnum = Integer.parseInt(portField.getText());
                    ss = new ServerSocket(portnum);                    
                    s = new server(portnum, console, ss);
                    s.start();
               }
               catch (Exception ex)
               {
                    ex.printStackTrace();
                    console.append("Server error: " + ex + "\n");
               }
          }
          else if(e.getSource() == close)
          {
               try
               {
                    socket.close();
               }
               catch(Exception ex)
               {
                    ex.printStackTrace();
               }
               setVisible(false);
               System.exit(0);
          }
          else if(e.getSource() == status)
          {
               //  check API for serversocket to count no, of conneciton.
               int count = s.activeCount();
               console.append("There are " + count + " number of clients connected");
          }
     }
     
     public static void main (String[] args)
     {
          fserver fs = new fserver();
          fs.setVisible(true);
         
          fs.addWindowListener
               (
               new WindowAdapter()
               {
                    public void windowClosing( WindowEvent e )
                    {
                         System.exit( 0 );
                    }
               }
               );
     }
}  // any ammendments here? looks fine for me..
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 

Author Comment

by:hywm
ID: 8173765
my clientgui

import java.util.*;
import java.net.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class fclient extends JFrame implements ActionListener
{
      private int portnum;
      private String ip;
      private ServerSocket server;
      private Socket socket;
      private DataOutputStream dos;
      private DataInputStream dis;
      private BufferedReader br;
      private PrintWriter pw;
      private File file;
      
      private JButton connect, disconnect, download, exit;
      private JScrollPane scroll;
      
      public fclient()
      {  
            super("Client");
            setSize(600, 350);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            mainpanel = new JPanel(new BorderLayout());
            
            // gui in north panel
            npanel = new JPanel();
            JLabel ipLabel = new JLabel("IP Address: ");
            ipField = new JTextField(15);
            JLabel portLabel = new JLabel("Port Number: ");
            portField = new JTextField(5);
            connect = new JButton("Connect");
            connect.addActionListener(this);
            disconnect = new JButton("Disconnect");
            disconnect.addActionListener(this);
            disconnect.setEnabled(false);
            npanel.add(ipLabel);
            npanel.add(ipField);
            npanel.add(portLabel);
            npanel.add(portField);
            npanel.add(connect);
            npanel.add(disconnect);
            
            console = new JTextArea();
            console.setEditable(false);
            scroll = new JScrollPane(console);
            
            spanel = new JPanel();
            JLabel enterFile = new JLabel("Enter file name: ");
            fileField = new JTextField(30);
            fileField.addActionListener(this);
            download = new JButton("Download");
            download.addActionListener(this);
            download.setEnabled(false);
            exit = new JButton("Exit");
            exit.addActionListener(this);
            exit.setEnabled(true);
            spanel.add(enterFile);
            spanel.add(fileField);
            spanel.add(download);
            spanel.add(exit);
            
            mainpanel.add(npanel, BorderLayout.NORTH);
            mainpanel.add(scroll, BorderLayout.CENTER);
            mainpanel.add(spanel, BorderLayout.SOUTH);
            
            setContentPane(mainpanel);
      }      
      
      public void actionPerformed(ActionEvent e)
      {
            if(e.getSource() == connect)
            {
                  try
                  {
                        ip = ipField.getText();
                        portnum = Integer.parseInt(portField.getText());
                        String emptyPort = portField.getText();
                        
                        if (ip.equals("") || emptyPort.equals(""))
                        {
                              console.append("Please enter an IP address and port no.\n");
                        }
                        else
                        {
                              socket = new Socket(ip, portnum);
                              
                              if (socket.isConnected() == false)
                              {
                                    console.append("Invalid ip or port no., please try again.\n");
                              }
                              else
                              {                  
                                    console.append("Connected to: " + socket.getInetAddress().getHostName() + "\n");                              
                                    download.setEnabled(true);
                                    connect.setEnabled(false);
                                    disconnect.setEnabled(true);
                                                                        dis      = new DataInputStream(socket.getInputStream());
                                    dos = new DataOutputStream(socket.getOutputStream());
                                    console.append("Got I/O streams.\n");                                    
                                    console.append("Server message: " + dis.readUTF() + "\n");
                                    console.append("Sending message \"Thank you.\" \n");
                                    dos.writeUTF("Thank you.\n");
                              }
                        }
                  }
                  catch (Exception ex)
                  {
                        ex.printStackTrace();
                        console.append(ex.getMessage());
                  }
            }
            else if(e.getSource()== download)
            {
                  try
                  {
                        pw.println(fileField);
                        // send filename to server, read and print lines
                        // from server until serve closes the connection
                        pw.println (fileField.getText());
                        pw.flush ( );
                        String line;
                        while ((line = br.readLine ( )) != null)
                        {
                              console.append(line);
                        }
                  }
                  catch (Exception ex)
                  {
                        ex.printStackTrace();      
                  }
            }
            else if(e.getSource()== disconnect)
            {
                  try
                  {
                        dos.writeUTF("Bye!\n");
                        socket.close();
                        // System.out.println("Disconnected from server.");
                        connect.setEnabled(true);
                        disconnect.setEnabled(false);
                        download.setEnabled(false);
                        console.setText("");
                        ipField.setText("");
                        portField.setText("");
                  }
                  catch (Exception ex)
                  {
                        ex.printStackTrace();
                  }
            }
            else if(e.getSource() == exit)
            {
                  setVisible(false);
                  System.exit(0);
            }
      }
      
      public static void main( String [] args)
      {
            fclient fc = new fclient();
            fc.setVisible(true);
            
            fc.addWindowListener
                  (
                  new WindowAdapter()
                  {
                        public void windowClosing( WindowEvent e )
                        {
                              System.exit( 0 );
                        }
                  }
                  );
      }
}

/* I cant decide which to use Datainputstream/Dataoutputstream  OR  bufferedReader, printwriter..   bufferedreader reads line and is definitely much faster, but disdos make things seems easier.., and how do the server listen to input streams all the while? seems to me that some client output is not caught when i was trying out my codes. and if thats the case how do we differentiate when it comes to lines of files from lines of messages for users??
I need help seriously =(
*/
0
 
LVL 4

Accepted Solution

by:
kokchoon78 earned 100 total points
ID: 8178823
Hi,

   I have just tested your codes, there are some compilation error on fclient.java, i think u manage to solve it.

   The connection of client and server is fine, both client and server can "talk" each other. The only problem is how to send file to client.
 
   
   For sending/copying file, BufferedReader.readLine() is not a good way, because it only suitable for text file but not binary file, e.g(*.exe).

The better way is :

   FileInputStream in = new FileInputStream(f);
   OuputStream out = socket.getOutputStream();
   byte[] buffer = new byte[1024];
   int read = -1;
   while ((read = in.read(buffer, 0, buffer.length)) != -1)
   {
       out.write(buffer, 0, read);
   }
}

Next, i also notice that the sendFile method is quite strange:

you defined the private PrintWriter pw;, but u never assign/ create a object on it. You must do something like :

pw = new PrintWriter( socket.getOutputStream(), true );


hth,
Kok Choon.
0
 

Author Comment

by:hywm
ID: 8186101
FileInputStream in = new FileInputStream(f);
  OuputStream out = socket.getOutputStream();

is there an error here?

it should be:
FileInputStream in = new FileInputStream();

right?

anyway im still working it out now, u haven pointed out good concept. Im left with no points now, so can i just work it out first before i paq this question? thanks =)
0
 

Author Comment

by:hywm
ID: 8186107
eh no, there should be a file argument inside....
sorry sorry ur right.
0
 

Author Comment

by:hywm
ID: 8186471
fis = new FileInputStream(f);
                         byte[] buffer = new byte[1024];                    
                         int eof = -1;
                         
                         while ((eof = fis.read(buffer)) != -1)
                         {
                             oos.write(buffer);
                         }
                         
                         oos.flush();

If this is the way my server sends the file, how isit tat my client is going to receive??? Can show me how? thanks alot
0
 
LVL 4

Expert Comment

by:kokchoon78
ID: 8192378
Hello:

i have amend some of your code, you may compare your original code. i have put in some description for the added code.

1) fclient.java

import java.util.*;
import java.net.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class fclient extends JFrame implements ActionListener
{
     private int portnum;
     private String ip;
     private ServerSocket server;
     private Socket socket;
     private DataOutputStream dos;
     private DataInputStream dis;
     private BufferedReader br;
     private PrintWriter pw;
     private File file;

     private JButton connect, disconnect, download, exit;
     private JScrollPane scroll;
     private JTextField ipField, portField, fileField;
     private JTextArea console;


     public fclient()
     {
          super("Client");
          setSize(600, 350);
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          JPanel mainpanel = new JPanel(new BorderLayout());

          // gui in north panel
          JPanel npanel = new JPanel();
          JLabel ipLabel = new JLabel("IP Address: ");
          ipField = new JTextField(15);
          JLabel portLabel = new JLabel("Port Number: ");
          portField = new JTextField(5);
          connect = new JButton("Connect");
          connect.addActionListener(this);
          disconnect = new JButton("Disconnect");
          disconnect.addActionListener(this);
          disconnect.setEnabled(false);
          npanel.add(ipLabel);
          npanel.add(ipField);
          npanel.add(portLabel);
          npanel.add(portField);
          npanel.add(connect);
          npanel.add(disconnect);

          console = new JTextArea();
          console.setEditable(false);
          scroll = new JScrollPane(console);

          JPanel spanel = new JPanel();
          JLabel enterFile = new JLabel("Enter file name: ");
          fileField = new JTextField(30);
          fileField.addActionListener(this);
          download = new JButton("Download");
          download.addActionListener(this);
          download.setEnabled(false);
          exit = new JButton("Exit");
          exit.addActionListener(this);
          exit.setEnabled(true);
          spanel.add(enterFile);
          spanel.add(fileField);
          spanel.add(download);
          spanel.add(exit);

          mainpanel.add(npanel, BorderLayout.NORTH);
          mainpanel.add(scroll, BorderLayout.CENTER);
          mainpanel.add(spanel, BorderLayout.SOUTH);

          setContentPane(mainpanel);
     }

     public void actionPerformed(ActionEvent e)
     {
          if(e.getSource() == connect)
          {
               try
               {
                    ip = ipField.getText();
                    portnum = Integer.parseInt(portField.getText());
                    String emptyPort = portField.getText();

                    if (ip.equals("") || emptyPort.equals(""))
                    {
                         console.append("Please enter an IP address and port no.\n");
                    }
                    else
                    {
                         socket = new Socket(ip, portnum);

                         if (socket.isConnected() == false)
                         {
                              console.append("Invalid ip or port no., please try again.\n");
                         }
                         else
                         {
                              console.append("Connected to: " + socket.getInetAddress().getHostName() + "\n");
                              download.setEnabled(true);
                              connect.setEnabled(false);
                              disconnect.setEnabled(true);
                                                            dis     = new DataInputStream(socket.getInputStream());
                              dos = new DataOutputStream(socket.getOutputStream());
                              console.append("Got I/O streams.\n");
                              console.append("Server message: " + dis.readUTF() + "\n");
                              console.append("Sending message \"Thank you.\" \n");
                              dos.writeUTF("Thank you.\n");
                         }
                    }
               }
               catch (Exception ex)
               {
                    ex.printStackTrace();
                    console.append(ex.getMessage());
               }
          }
          else if(e.getSource()== download)
          {
               try
               {
                            //Changed by Ling Kok Choon
                            //send file name to server
                            pw = new PrintWriter( socket.getOutputStream(), true);
                    pw.println (fileField.getText());
                    pw.flush ( );


                    //Wait for response from server
                    //Changed by Ling Kok Choon
                    InputStream is = socket.getInputStream();

                    //The output file is out.txt, you may put the out file as fileField.getText()
                    String outFilePath = "C:\\temp\\out.txt";
                    File outFile = new File ( outFilePath );
                    FileOutputStream fos = new FileOutputStream(outFile);
                    int eof = -1;

                    console.append("Receiving File from server ...");
                    int byteCount = 0 ;
                    while ((eof = is.read()) != -1)
                    {
                        fos.write(eof);
                        byteCount ++;
                    }
                    fos.flush();
                    fos.close();

                    console.append("Transmission Completed...\n Total " + Integer.toString(byteCount) + "bytes received\n");
                    console.append("The output file is located at :" + outFilePath + "\n");
               }
               catch (Exception ex)
               {
                    ex.printStackTrace();
               }
          }
          else if(e.getSource()== disconnect)
          {
               try
               {
                    dos.writeUTF("Bye!\n");
                    socket.close();
                    // System.out.println("Disconnected from server.");
                    connect.setEnabled(true);
                    disconnect.setEnabled(false);
                    download.setEnabled(false);
                    console.setText("");
                    ipField.setText("");
                    portField.setText("");
               }
               catch (Exception ex)
               {
                    ex.printStackTrace();
               }
          }
          else if(e.getSource() == exit)
          {
               setVisible(false);
               System.exit(0);
          }
     }

     public static void main( String [] args)
     {
          fclient fc = new fclient();
          fc.setVisible(true);

          fc.addWindowListener
               (
               new WindowAdapter()
               {
                    public void windowClosing( WindowEvent e )
                    {
                         System.exit( 0 );
                    }
               }
               );
     }
}
0
 
LVL 4

Expert Comment

by:kokchoon78
ID: 8192380
2) server.java

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

public class server extends Thread
{
     private File f;
     private int portnum;
     private JTextArea console;
     private Socket socket;
     private ServerSocket server;
     private int noOfCon = 0;
     private DataOutputStream dos;
     private DataInputStream dis;

     public server(int portnum, JTextArea console, ServerSocket server)
     {
          this.portnum = portnum;
          this.console = console;
          this.server = server;
     }

     public void run()
     {
          try
          {
               console.append("Listening for connections on port " + portnum + " ... \n");
               while(true)
               {
                    socket = server.accept();
                    console.append("Received connection from " + socket.getInetAddress().getHostName() + "\n");

                    noOfCon++;
                    console.append("There is / are " + noOfCon + " connection/s  \n");
                    ConnectionHandler ch = new ConnectionHandler(socket);

               }
          }
          catch(Exception e)
          {
               e.printStackTrace();
               console.append(e.getMessage());
          }
     }


     class ConnectionHandler extends Thread
     {
          private Socket socket;
          private PrintWriter pw;
          private BufferedReader br;

          public ConnectionHandler(Socket socket)
          {
               this.socket = socket;
               start();
          }

          public void sendFile(String filename) throws Exception
          {
               f = new File(filename);
               if ((! f.exists()) || f.isDirectory())
               {
                        pw = new PrintWriter( socket.getOutputStream());
                    pw.println("File error,Pls enter a valid file\n");
                    pw.close();
               }
               else
               {
                         FileInputStream fis = new FileInputStream(f);
                         OutputStream oos = socket.getOutputStream();

                    int eof = -1;
                    while ((eof = fis.read()) != -1)
                    {
                        oos.write(eof);
                    }
                    oos.flush();
                    oos.close();
               }
          }


          public void run()
          {
               try
               {
// im using datai/ostreams to print the messages on console, but what about file sending? can i use the same stream thruout? disdos or buffered/printwrite?
                    dis = new DataInputStream(socket.getInputStream());
                    dos = new DataOutputStream(socket.getOutputStream());
                    console.append("Got I/O streams.\n");

                    console.append("Sending message \"Connection successful\" \n");
                    dos.writeUTF("Connection successful");
                    console.append("Client message: " + dis.readUTF());

                    // file sending here..
                    br = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
                    String filename = br.readLine();

                    sendFile(filename);
               }
               catch (Exception e)
               {
                    e.printStackTrace();
                    console.append(e.getMessage() + "\n");
               }

               finally
               {
                    try
                    {
// either disdos or pw/br here....
                         br.close();
                         socket.close();
                    }
                    catch (IOException e)
                    {}
               }

          }
     } // end connectionhandler class


}
0
 
LVL 4

Expert Comment

by:kokchoon78
ID: 8192383
3) fserver.java

import java.util.*;
import java.net.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class fserver extends JFrame implements ActionListener
{
    private int portnum;    
    private Socket socket;
    private ServerSocket ss;
    private server s;
   
    // GUI panels. n stands for north s for south and c for centre
    private JPanel mainpanel, npanel, spanel;
    private JTextArea console;
    private JTextField portField;
    // status to display no. of current connection, listen to start waiting for connection
    private JButton listen, status, close;
    private JScrollPane scroll;
   
    public fserver()
    {  
         super("Server");
         //this.server = server;
         //this.socket = socket;
         setSize(600, 350);
         setDefaultCloseOperation(EXIT_ON_CLOSE);
         mainpanel = new JPanel(new BorderLayout());
         
         // gui in north panel
         npanel = new JPanel();
         JLabel pn = new JLabel("Port Number: ");
         portField = new JTextField(8);
         listen = new JButton("Listen");
         listen.addActionListener(this);
         npanel.add(pn);
         npanel.add(portField);
         npanel.add(listen);
         
         //cpanel = new JPanel();
         console = new JTextArea();
         console.setEditable(false);
         scroll = new JScrollPane(console);
         //cpanel.add(console);
         
         spanel = new JPanel();
         status = new JButton("Status");
         status.setEnabled(false);
         close = new JButton("Close");
         close.addActionListener(this);
         spanel.add(status);
         spanel.add(close);
         
         mainpanel.add(npanel, BorderLayout.NORTH);
         mainpanel.add(scroll, BorderLayout.CENTER);
         mainpanel.add(spanel, BorderLayout.SOUTH);
         
         setContentPane(mainpanel);
    }    
   
    public void actionPerformed(ActionEvent e)
    {
         if(e.getSource() == listen)
         {
              try
              {
                   status.setEnabled(true);
                   portnum = Integer.parseInt(portField.getText());
                   ss = new ServerSocket(portnum);                    
                   s = new server(portnum, console, ss);
                   s.start();
              }
              catch (Exception ex)
              {
                   ex.printStackTrace();
                   console.append("Server error: " + ex + "\n");
              }
         }
         else if(e.getSource() == close)
         {
              try
              {
                   socket.close();
              }
              catch(Exception ex)
              {
                   ex.printStackTrace();
              }
              setVisible(false);
              System.exit(0);
         }
         else if(e.getSource() == status)
         {
              //  check API for serversocket to count no, of conneciton.
              int count = s.activeCount();
              console.append("There are " + count + " number of clients connected");
         }
    }
   
    public static void main (String[] args)
    {
         fserver fs = new fserver();
         fs.setVisible(true);
         
         fs.addWindowListener
              (
              new WindowAdapter()
              {
                   public void windowClosing( WindowEvent e )
                   {
                        System.exit( 0 );
                   }
              }
              );
    }
}  


hth,
Kok Choon.
0
 

Author Comment

by:hywm
ID: 8203096
Thanks alot, but there is still some programming logic i need to clarify, but with my lecturer. Thanks anyway, u have given useful help nonetheless =). Im pointless now, guess thats where i end talking in experts exchange. byee~~~~
0
 

Author Comment

by:hywm
ID: 8203099
Thanks alot, but there is still some programming logic i need to clarify, but with my lecturer. Thanks anyway, u have given useful help nonetheless =). Im pointless now, guess thats where i end talking in experts exchange. byee~~~~
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Suggested Courses
Course of the Month10 days, 14 hours left to enroll

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question