The third server and client program is about the file transfering .....
FileServer. java:
[Java]
Import java.net .*;
Import java. io .*;
Public class FileServer {
Public static void main (String [] args) throws IOException {
// Create socket
ServerSocket servsock = new ServerSocket (1234 );
While (true ){
System. out. println ("File Server Waiting for Client ...");
Socket sock = servsock. accept ();
System. out. println ("Accepted connection:" + sock );
// Sendfile
File myFile = new File ("CSD.ppt ");
Byte [] mybytearray = new byte [(int) myFile. length ()];
FileInputStream FCM = new FileInputStream (myFile );
BufferedInputStream bis = new BufferedInputStream (FCM );
Bis. read (mybytearray, 0, mybytearray. length );
OutputStream OS = sock. getOutputStream ();
System. out. println ("Sending ...");
OS. write (mybytearray, 0, mybytearray. length );
OS. flush ();
Sock. close ();
}
}
}
FileClient. java:
[Java]
Import java.net .*;
Import java. io .*;
Public class FileClient {
Public static void main (String [] args) throws IOException {
Int filesize = 6022386; // filesize temporary hardcoded
Long start = System. currentTimeMillis ();
Int bytesRead;
Int current = 0;
// Localhost for testing
Socket sock = new Socket ("127.0.0.1", 1234 );
System. out. println ("Connecting ...");
// Receive file
Byte [] mybytearray = new byte [filesize];
InputStream is = sock. getInputStream ();
FileOutputStream fos = new FileOutputStream ("CSD.ppt ");
BufferedOutputStream bos = new BufferedOutputStream (fos );
BytesRead = is. read (mybytearray, 0, mybytearray. length );
Current = bytesRead;
Do {
BytesRead =
Is. read (mybytearray, current, (mybytearray. length-current ));
If (bytesRead> = 0) current + = bytesRead;
} While (bytesRead>-1 );
Bos. write (mybytearray, 0, current );
Bos. flush ();
Long end = System. currentTimeMillis ();
System. out. println (end-start );
Bos. close ();
Sock. close ();
}
}
Goal: the file server sends the csd.ppt to file client:
The following gif is the test result: