Saturday, November 21, 2009

File Server using UDP

In this file server example , there is a Client and Server program .
First of all please start the Server then after that start the client.
Note: In this example the client and server need to run from the same machine. You could change this settings and it would take only few steps.

Server.java


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Server extends JFrame{
JPanel jpTop , jpBottom ;
Container cont ;
JButton browse , start ,stop ,cancel ;
JTextField jtxtFld ;

DatagramSocket ds ;
DatagramPacket dp ;

FileInputStream fileInS ;
File selectedFile ;

InetAddress clientAddress ;
int port ;

String validFileName ;
boolean finalization = false ;

Runnable shutDownThread = new Runnable(){
public void run() {
if(!finalization)
shutDownOperations() ;
}
};

void initGUI(){
this.setTitle("Server") ;
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
this.setVisible(true) ;

cont = this.getContentPane() ;
cont.setLayout(new BoxLayout(cont,BoxLayout.Y_AXIS)) ;

jpTop = new JPanel() ;
jtxtFld = new JTextField(30) ;
jtxtFld.setFont(new Font(Font.SANS_SERIF,Font.PLAIN,20)) ;
jtxtFld.setEditable(false) ;
browse = new JButton("Browse") ;
jpTop.add(jtxtFld) ;
jpTop.add(browse) ;

jpBottom = new JPanel() ;
start = new JButton("Start") ;
start.setEnabled(false) ;
stop = new JButton("Stop") ;
stop.setEnabled(false) ;
cancel = new JButton("Cancel") ;
jpBottom.add(start) ;
jpBottom.add(stop) ;
jpBottom.add(cancel) ;

cont.add(jpTop) ;
cont.add(jpBottom) ;

this.pack() ;
}

void initListeners(){
browse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
selectedFile = fileChooser.getSelectedFile();
validFileName = selectedFile.getName() ;
jtxtFld.setText(selectedFile.getAbsolutePath()) ;
start.setEnabled(true) ;
}
}
});
start.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
start.setEnabled(false) ;
stop.setEnabled(true) ;
browse.setEnabled(false) ;
try{
initServer() ;
}catch(Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage()) ;
}
}
});
stop.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
stop.setEnabled(false) ;
start.setEnabled(true) ;
browse.setEnabled(true) ;
shutDownOperations() ;
}
}) ;
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
shutDownOperations() ;
System.exit(0) ;
}
}) ;
}
void initServer()throws Exception{


fileInS = new FileInputStream(selectedFile) ;

long fileSize = selectedFile.length() ;


String msg = validFileName+"\n"+fileSize ;
System.out.println(msg) ;
ds = new DatagramSocket(2000) ;
dp = new DatagramPacket(new byte[8192],8192) ;

//Server waits for the client to make a request
ds.receive(dp) ;

clientAddress = dp.getAddress() ;
port = dp.getPort() ;

dp.setData(new byte[8192]) ;
dp.setLength(8192) ;

//send to the client the Filename and size
dp.setPort(port) ;
dp.setAddress(clientAddress) ;
dp.setData(msg.getBytes()) ;
dp.setLength(msg.length()) ;

ds.send(dp) ;

byte[] data = new byte[8192] ;
int ret = 0 ;
try{
while(true){
ret = fileInS.read(data) ;
if(ret==-1)break ;
dp.setData(data) ;
dp.setLength(data.length) ;
Thread.sleep(100) ;
ds.send(dp);
}
byte val[] = new byte[2] ; val[0] = val[1] = 0 ;
dp.setData(val) ;
dp.setLength(2) ;
// a 2 byte packet denotes end of file
ds.send(dp) ;
}catch(Exception ex){
JOptionPane.showMessageDialog(null,"Error occured during write operation") ;
throw new Exception(ex.getMessage()) ;
}
}
void shutDownOperations(){
try{ds.close() ;}catch(Exception e){e.printStackTrace();}
try {
fileInS.close() ;
} catch (IOException e) {
e.printStackTrace();
}
finalization = true ;
}
public Server(){
initGUI() ;
initListeners() ;
Runtime.getRuntime().addShutdownHook(new Thread(shutDownThread)) ;
}
public static void main(String args[]){
Server server = new Server() ;
}
}





Client.java


import java.lang.reflect.InvocationTargetException;
import java.net.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;

import java.awt.event.*;
public class Client {
DatagramSocket ds ;
DatagramPacket dp ;

JProgressBar jprg ;

FileOutputStream fout ;

String fileName ="" ;
String size ;
String name ;

String destinationFolder ;
volatile boolean flag = true ;

Runnable shutDownHook = new Runnable(){
public void run() {
flag = false ;
shutDownOperations() ;
}
};

Runnable progressMonitor = new Runnable(){
public void run() {
System.out.println("Inside progressmonitor") ;
long originalSize = Long.valueOf(size.trim()) ;
File filevar = new File(name) ;
int percent = 0 ;

jprg = new JProgressBar() ;
jprg.setMinimum(0) ;
jprg.setMaximum(100) ;
jprg.setStringPainted(true) ;

JFrame jf = new JFrame("File Downloading...") ;
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
jf.add(jprg) ;
jf.setVisible(true) ;
jf.pack() ;

while(flag){
try {
Thread.sleep(100) ;
} catch (InterruptedException e) {}

percent = (int) (((filevar.length())/originalSize)*100) ;
jprg.setValue(percent) ;
}
}
};
void initServer()throws Exception{
ds = new DatagramSocket() ;
dp = new DatagramPacket(new byte[8192],8192,InetAddress.getLocalHost(),2000) ;

String msg = "connect request" ;

dp.setData(msg.getBytes()) ;
dp.setLength(msg.length()) ;
// sends connect request to server
ds.send(dp) ;

dp.setData(new byte[8192]) ;
dp.setLength(8192) ;
//collects file information from Server[details are fileName and size]
ds.receive(dp) ;

msg = new String(dp.getData(),0,dp.getLength(),"ASCII") ;
//System.out.println(msg) ;
char ch = 'a' ;
for(int i=0 ; i< msg.length() ; i++){
ch = msg.charAt(i) ;
if(ch=='\n'){
size = msg.substring(i+1) ;
break ;
}
fileName += ch ;
}

}
void selectDestinationFolder(){
JFileChooser fileChooser = new JFileChooser(".");
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setDialogTitle("Select Destination to store File") ;
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile() ;
destinationFolder = file.getAbsolutePath() ;
}
else if(returnValue == JFileChooser.CANCEL_OPTION){
System.exit(0) ;
}
}
void fileDownload()throws FileNotFoundException{
name = destinationFolder+File.separatorChar+fileName ;
System.out.println("File name = "+name) ;
System.out.println("File size = "+size) ;
fout = new FileOutputStream(name) ;

System.out.println("Starting downloading file...........") ;

Thread pgbar = new Thread(progressMonitor) ;
pgbar.start() ;


try{
while(true){
dp.setData(new byte[8192]) ;
dp.setLength(8192) ;
ds.receive(dp) ;
if(dp.getLength() == 2)break ;
fout.write(dp.getData()) ;
}
}catch(Exception ex){
ex.printStackTrace() ;
}
System.out.println("\n\n.........Download Complete") ;
}
void shutDownOperations(){
try{
ds.close() ;
fout.close() ;
}catch(Exception ex){
ex.printStackTrace() ;
}
}
public Client(){
selectDestinationFolder() ;
try{
initServer() ;

fileDownload() ;
}catch(Exception ex){
ex.printStackTrace() ;
}

Runtime.getRuntime().addShutdownHook(new Thread(shutDownHook)) ;
}

public static void main(String[] args){
Client client = new Client() ;
}
}


OUTPUT


Server





Client

No comments:

Post a Comment