السلام عليكم ،
هذا مثال على Files Server كتبته زمان ..
الكلاينت يستعلم عن وجود الملف عند السيرفر ، أذا الملف موجود ، يرسل السيرفر معلومات عن الملف .. بعدها السيرفر يرسل الملف الى الكلاينت ..
استخدمت فيه UDP & TCP
ال UDP استخدمته فقط للاستعلام عن وجود الملف
الTCP لنقل الملف الى الكلاينت والتاكد من سلامة الملف .
نرحب باي تعديلات :)
Client.java
import java.io.*;
import java.net.*;
public class Client {
static int TCP_PORT;
static int UDP_PORT=3456;
static File file=null;
public static void main(String args[]) throws Exception{
System.out.println("Start UDP Connection ,,,");
// get fileName from user
BufferedReader console=new BufferedReader(new InputStreamReader(System.in));
// prepare for UDP connection
DatagramSocket clientSocket =new DatagramSocket();
InetAddress IP=InetAddress.getByName("localhost");
// data streams from/to client
byte [] sendData=new byte[1024];
byte [] receiveData=new byte[1024];
System.out.println(" Enter File name with extenstion :");
System.out.println("");
// cmd=file name[e.g. file1.txt ]
String cmd=console.readLine();
sendData=cmd.getBytes();
//prepare packet that contain client data
DatagramPacket sendPacket= new DatagramPacket(sendData,sendData.length,IP,UDP_PORT);
// send the packet to the server
clientSocket.send(sendPacket);
System.out.println("file name sent ...");
// prepare packet that contain server response/data
DatagramPacket receivePacket=new DatagramPacket(receiveData,receiveData.length);
// receive it
clientSocket.receive(receivePacket);
//convert it to String
String response=new String(receivePacket.getData());
System.out.println(response);
// if the file found
if(!response.contains("NOT Found")){
int index=response.indexOf("port");
// extract port number for the TCP connection
TCP_PORT=Integer.parseInt(response.substring(index+5).trim());
System.out.println("Download Port is :"+TCP_PORT);
// Close the UDP connection
clientSocket.close();
System.out.println("UDP Connection closed ,, ");
clientSocket.close();
/* start TCP connection
*IP=IP for the server ( e.g. localhost[172.0.0.1] )
*TCP_PORT = the port that server listeneing on
*/
Socket s=null;
try{
s=new Socket(IP,TCP_PORT);
}
catch(Exception e){
System.out.println("Server not responding \n reconnect");
}
System.out.println("");
System.out.println("TCP connection start ,,");
System.out.println("");
// prepare to send data to the server
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
// get fileName [e.g. get file1.txt ]
cmd=console.readLine();
// send it to the server
out.println(cmd);
/*
*while server return File Object
*we need to get that file as Object
*Here we deserialize the object
*/
File FileObject=null;
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
try{
FileObject = (File) in.readObject();
}
catch(Exception e)
{
System.out.println("ERROR on File Download \n Enter correct fileName\n [e.g. get file.txt ]");
}
System.out.println("File PATH on Server :"+FileObject);
BufferedWriter bw=new BufferedWriter(new FileWriter("fromServer_"+FileObject.getName()));
// Read the file
BufferedReader brr=new BufferedReader(new FileReader(FileObject));
String line;
while((line=brr.readLine())!=null)
{
bw.write(line);
bw.newLine();
bw.flush();
System.out.println(line);
}
System.out.println("TCP connection closed ,, ");
System.out.println("Bye , Bye ..");
s.close();
}
else{ // if the file not found close connection
System.out.println("Bye , Bye ..");
System.out.println("UDP connection closed ..");}
}
}Server.java
import java.io.*;
import java.net.*;
class Server {
// SERVER_PATH = FOLDER IN THE SERVER THAT CONTAINS FILES
static File SERVER_PATH=new File("/Users/eisa/JavaApplication1");
static int SERVER_PORT = 3222;
static int UDP_PORT=3456;
static BufferedReader inputs=null;
static ObjectOutputStream outputs=null;
public static void main(String args[]) throws Exception{
// prepare data streams/bytes from/to server
byte[] inputsBytes =new byte[1024];
byte[] outputsBytes=new byte[1024];
// client = client socket that binding with the server
Socket client;
ServerSocket server = null;
// start listening for UDP connection
DatagramSocket UDPSocket =null;
try{
UDPSocket=new DatagramSocket(UDP_PORT);
server = new ServerSocket(SERVER_PORT);
}
catch(Exception e)
{
System.out.println("ERROR : Server cannot connect ");
}
while(true)
{
// prepare packet contains client data
DatagramPacket inputPacket=new DatagramPacket(inputsBytes,inputsBytes.length);
// receive it
UDPSocket.receive(inputPacket);
// convert it to string
String cmd =new String(inputPacket.getData());
// get the ip
InetAddress IP=inputPacket.getAddress();
//get the port for client port
int port =inputPacket.getPort();
// Check method checks if the file exist or not
String response =Check(cmd);
outputsBytes=response.getBytes();
DatagramPacket outputPacket= new DatagramPacket(outputsBytes,outputsBytes.length,IP,port);
// send packet contains server response
UDPSocket.send(outputPacket);
// UDP closed and start TCP ( depending on the server response )
System.out.println("TCP : SERVER Listening on port " + SERVER_PORT);
client = server.accept();
String input=null;
try {
// inputs always String
// but the output always File Objects
inputs = new BufferedReader(new InputStreamReader(client.getInputStream()) );
outputs = new ObjectOutputStream( client.getOutputStream() );
// get the client command
input = inputs.readLine();
// accept get
if (input.startsWith("get")){
// omittted get and spaces
String fileName = input.substring(3).trim();
sendFile(fileName);
}
else
throw new Exception("ERROR PLEASE ENTER [get fileName.ext");
}
catch (Exception e) {
System.out.println("ERROR IN DATA ");
}
finally {
client.close();
}
}
}
static void sendFile(String fileName) throws Exception {
File file = new File(SERVER_PATH,fileName);
if(file.isFile()){
// send File Object to the client
outputs.writeObject(file);
outputs.close();
}
}
static String Check(String fileName) throws IOException{
String out="File NOT Found !";
fileName=fileName.trim();
File file=new File(SERVER_PATH,fileName);
if(file.exists())
{
out="File found with size "+ file.length()+" bytes \n" +
"File readable "+file.canRead()+"\n"+
"you can download it via port "+SERVER_PORT;
}
return out;
}
}