File Transfer Using Java Sockets
File Transfer Using Java Sockets
File Transfer Using Java Sockets
01.09.2010
AIM:
To demonstrate file transfer using Java Sockets.
DESCRIPTION:
Socket class:
The creation of Socket class object is used to establish connection between the client and
the server. It is contained in the java.net package.
Creating instance of Socket class:
Syntax:
Socket s= new Socket (String hostname, int port);
ServerSocket class:
ServerSocket runs on the server side and listens to incoming TCP connections. Each
ServerSocket listens on a particular port on the server side.
Creating instance of ServerSocket class:
Syntax:
ServerSocket s= new ServerSocket(int port);
FileInputStream class:
It creates an InputStream that can be used to read bytes from a file.
Creating instance of FileInputStream class:
Syntax:
FileInputStream fos= new FileInputStream(String Filepath);
FileOutputStream class:
It creates an OutputStream that can be used to write bytes to a file.
Creating instance of FileOutputStream class:
Syntax:
FileOutputStream fos= new FileOutputStream(String Filepath);
DataInputStream class:
It is an InputStream that contains methods for reading the Java standard data types.
Creating instance of DataInputStream class:
Syntax:
DataInputStream dis=new DataInputStream(s.getInputStream());
Where s is an Socket object and the getInputStream method returns an
InputStream that can read data from a socket.
DataOutputStream class:
It is an OutputStream that contains methods for writing the Java standard data types.
Creating instance of DataOutputStream class:
Syntax:
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
Where s is an Socket object and the getOutputStream method returns an
OutputStream that can read data from an application to the other end of the socket.
ALGORITHM:
Server Side:
Client Side:
//Server.java
import java.net.*;
import java.io.*;
public class server
{
public static void main(String[] args) throws Exception
{
//Client.java
import java.io.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
}
public void actionPerformed(ActionEvent ae)
{
//socketconnection
try
{
Socket c1=new Socket("127.0.0.1",2234);
int s;
DataInputStream dis=new DataInputStream(System.in);
l.setText("Connected Successfully..");
String filename=tf.getText();
String f2=t2.getText();
DataOutputStream dos=new
DataOutputStream(c1.getOutputStream());
dos.writeBytes(filename);
dos.writeBytes("\n");
DataInputStream in=new DataInputStream(c1.getInputStream());
FileWriter fw=new FileWriter(f2);
BufferedWriter bw=new BufferedWriter(fw);
while((s=in.read())!=-1)
{
System.out.print((char)s);
bw.write(s);
g+=(char)s;
aa.setText(g);
}
dos.close();
dis.close();
in.close();
bw.close();
fw.close();
}
catch(Exception e)
{
}
}
public void windowClosing(WindowEvent e){ System.exit(0); }
public static void main(String[] args) throws Exception
{
gclient s=new gclient();
}
}
Sample Output: