Practical : 2
Subject : Advanced Java
Aim : Implement TCP Server for transferring files using Socket and ServerSocket.
Server Code:
--------------------------------------------------------------------------------
import java.io.*;
import java.net.*;
class Server
{
public
static void main(String args[]) throws Exception
{
ServerSocketss=new
ServerSocket(7777);
Socket
s=ss.accept();
System.out.println("connected..........");
FileInputStream
fin=new FileInputStream("Send.txt");
DataOutputStreamdout=new
DataOutputStream(s.getOutputStream());
int
r;
while((r=fin.read())!=-1)
{
dout.write(r);
}
System.out.println("\nFiletranfer
Completed");
s.close();
ss.close();
}
}
--------------------------------------------------------------------------------
Client Code:
--------------------------------------------------------------------------------
import java.io.*;
import java.net.*;
public class Client {
public
static void main(String[] args) throws Exception
{
Socket
s=new Socket("127.0.0.1",7777);
if(s.isConnected())
{
System.out.println("Connected
to server");
}
FileOutputStreamfout=
new FileOutputStream("received.txt");
DataInputStream
din=new DataInputStream(s.getInputStream());
int
r;
while((r=din.read())!=-1)
{
fout.write((char)r);
}
s.close();
}
}
--------------------------------------------------------------------------------
Output:
Server
Client
Sent File
Received File
Sign up here with your email
3 comments
Write commentsnot working
Replyit's working ... you need to change some code.
ReplySERVER:
import java.io.*;
import java.net.*;
class Server2
{
public static void main(String args[]) throws Exception
{
try (ServerSocket ss = new ServerSocket(7777); Socket s = ss.accept()) {
System.out.println("connected..........");
FileInputStream fin=new FileInputStream("Send.txt");
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
int r;
while((r=fin.read())!=-1)
{
dout.write(r);
}
System.out.println("\nFiletranfer Completed");
}
}
}
CLIENT:
import java.io.*;
import java.net.*;
/**
*
* @author jigar
*/
public class Client2 {
public static void main(String[] args) throws Exception
{
try (Socket s = new Socket("127.0.0.1",7777)) {
if(s.isConnected())
{
System.out.println("Connected to server");
}
FileOutputStream fout;
fout = new FileOutputStream("received.txt");
DataInputStream din=new DataInputStream(s.getInputStream());
int r;
while((r=din.read())!=-1)
{
fout.write((char)r);
}
}
}
}
how i import text file
ReplyConversionConversion EmoticonEmoticon