MyServer.java
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
static int port = 5000;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
System.out.println("Accepted connection : " + socket);
File transferFile = new File("Document.doc");
byte[] bytearray = new byte[(int) transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray, 0, bytearray.length);
OutputStream os = socket.getOutputStream();
System.out.println("Sending Files...");
os.write(bytearray, 0, bytearray.length);
os.flush();
socket.close();
System.out.println("File transfer complete");
}
}
MyClient.java
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class MyClient {
public static void main(String[] args) throws IOException {
int bytesRead;
int currentTot = 0;
Socket socket = new Socket("127.0.0.1", 5000);
byte[] bytearray = new byte[65000];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("copy.doc");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray, 0, bytearray.length);
currentTot = bytesRead;
do {
bytesRead = is.read(bytearray, currentTot, (bytearray.length - currentTot));
if (bytesRead >= 0)
currentTot += bytesRead;
} while (bytesRead > -1);
bos.write(bytearray, 0, currentTot);
bos.flush();
bos.close();
socket.close();
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.