File Transfer using Socket in JAVA :
Client Program:
MyClient.java
______________________________________________________________________________
______________________________________________________________________________
import java.net.*;
import java.io.*;
class MyClient {
public static void main(String srgs[])throws IOException
{
Socket s=null;
BufferedReader get=null;
PrintWriter put=null;
try
{
s=new Socket("127.0.0.1",8081);
get=new BufferedReader(new InputStreamReader(s.getInputStream()));
put=new PrintWriter(s.getOutputStream(),true);
}
catch(Exception e)
{
System.exit(0);
}
String u,f;
System.out.println("Enter the file name to transfer from server:");
DataInputStream dis=new DataInputStream(System.in);
f=dis.readLine();
put.println(f);
File f1=new File("c:\\output");
FileOutputStream fs=new FileOutputStream(f1);
while((u=get.readLine())!=null)
{
byte jj[]=u.getBytes();
fs.write(jj);
}
fs.close();
System.out.println("File received");
s.close();
}
}
______________________________________________________________________________
Server Program:
FileServer.java
______________________________________________________________________________
import java.io.*;
import java.net.*;
public class FileServer {
public static void main(String args[])throws IOException
{
ServerSocket ss=null;
try
{
ss=new ServerSocket(8081);
}
catch(IOException e)
{
System.out.println("couldn't listen");
System.exit(0);
}
Socket cs=null;
try
{
cs=ss.accept();
System.out.println("Connection established"+cs);
}
catch(Exception e)
{
System.out.println("Accept failed");
System.exit(1);
}
PrintWriter put=new PrintWriter(cs.getOutputStream(),true);
BufferedReader st=new BufferedReader(new InputStreamReader(cs.getInputStream()));
String s=st.readLine();
System.out.println("The requested file is : "+s);
File f=new File(s);
if(f.exists())
{
BufferedReader d=new BufferedReader(new FileReader(s));
String line;
while((line=d.readLine())!=null)
{
put.write(line);
put.flush();
}
d.close();
System.out.println("File transfered");
cs.close();
ss.close();
}
}
}
______________________________________________________________________________
No comments:
Post a Comment