Operating Systems For Linux/Ubunbtu, create and configure a client / server architecture that allows the following operations with files from / to the client: -Copy, move, delete. -Chat between users that allows the exchange of files, including videos.
I already did this as a part of one of the assignments (Where I
also made groups for users where user can share messages and files
in groups)
FileClient.java:
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.*;
import java.io.*;
import java.util.*;
import java.net.InetAddress;
public class FileClient extends Thread {
public static String nameport;
public static void TrasferStatus(long a, long b)
{
//Function to Print the Status bar.
System.out.println("File Transfer Complete Status: ");
int percentage =(int) ((a*100)/b);
System.out.printf("[");
for(int k=0;k<percentage/10;k++)
System.out.printf("=");
for(int k=percentage/10;k<10;k++)
System.out.printf(" ");
System.out.println("] " + String.valueOf(percentage) + "%");
}
public static void main(String[] args) {
int type =0;
int client_port=3333,udp_client_port=9000;
String nameport="thisuser";
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
int bufferSize = 0;
String serverip ="localhost";
String str1="",str2="";
String ourip ="";
try{
InetAddress inetAddresslocal = InetAddress.getLocalHost();
ourip = inetAddresslocal.getHostAddress();
System.out.println(ourip);
}
catch(IOException e)
{
System.out.println("Error in reading Buffer: Please Check");
}
while(true)
{
//Running the Client part in this loop(main thread.)
BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
System.out.printf("$>>");
try
{
str1=buffer.readLine();
}
catch(IOException e)
{
System.out.println("Error in reading Buffer: Please Check");
}
BufferedOutputStream bufferOutStream=null;
String[] commands = str1.split(" ");
String cmp1 = "upload",cmp2 ="upload_udp",cmp3="create_folder",cmp4="move_file",cmp5="create_user",cmp6="create_group",cmp7="list_groups";
String cmp8 = "join_group",cmp9 = "leave_group",cmp10 = "list_detail",cmp11 = "get_file",cmp12 = "share_msg";
if(commands[0].equals(cmp12)){
try{
//to other pc //Connect
// Socket s= new Socket("10.1.34.33",client_port);
Socket s= new Socket(serverip,client_port);
DataInputStream dataInpStream=new DataInputStream(s.getInputStream());
DataOutputStream dataOutStream=new DataOutputStream(s.getOutputStream());
byte[] contents;
String msg = "";
for(int i=1;i<commands.length;i++){
msg += commands[i];
msg += " ";
}
dataOutStream.writeUTF("sharemsg"+":" + msg);
System.out.println("Message Sent to Server Completed");
String response = "";
response = dataInpStream.readUTF();
System.out.println(response);
dataOutStream.flush();
dataInpStream.close();
s.close();
}
catch(IOException ex)
{
System.out.println("Unable to Move the Files " + commands[1]);
}
}
if(commands.length == 3){
if(commands[0].equals(cmp4)){
try{
//to other pc //Connect
// Socket s= new Socket("10.1.34.33",client_port);
Socket s= new Socket(serverip,client_port);
DataInputStream dataInpStream=new DataInputStream(s.getInputStream());
DataOutputStream dataOutStream=new DataOutputStream(s.getOutputStream());
byte[] contents;
dataOutStream.writeUTF("start"+":" + commands[0] +":"+commands[1]+":"+commands[2]+":"+ourip+":"+nameport+":"+"move");
System.out.println("Move File Completed");
dataOutStream.flush();
dataInpStream.close();
s.close();
}
catch(IOException ex)
{
System.out.println("Unable to Move the Files " + commands[1]);
}
}
}
if(commands.length == 1){
if(commands[0].equals(cmp7)){
try{
Socket s = new Socket(serverip,client_port);
DataInputStream dataInpStream = new DataInputStream(s.getInputStream());
DataOutputStream dataOutStream = new DataOutputStream(s.getOutputStream());
dataOutStream.writeUTF("list"+":"+commands[0]+":"+ourip+":"+"listgroups");
System.out.println("Following are the list of groups available");
String response ="";
response = dataInpStream.readUTF();
System.out.println(response);
dataOutStream.flush();
dataInpStream.close();
s.close();
}
catch(IOException e){
System.out.println("Cant list the groups needed");
}
}
}
if(commands.length == 2){
if(commands[0].equals(cmp11)){
try{
// System.out.print("Enter the file name");
String[] fname = commands[1].split("/");
String filename ="";
for(int i=0;i<fname.length;i++){
filename = fname[i];
}
Socket s = new Socket(serverip,client_port);
// sending the file name to server. Uses PrintWriter
OutputStream ostream = s.getOutputStream( );
DataOutputStream dataOutStream = new DataOutputStream(s.getOutputStream());
String namegrp = commands[1];
dataOutStream.writeUTF("Get"+":" + commands[0] +":"+nameport+":"+namegrp+":"+"getfile");
// receiving the contents from server. Uses input stream
InputStream istream = s.getInputStream();
BufferedReader socketRead = new BufferedReader(new InputStreamReader(istream));
String str;
while((str = socketRead.readLine()) != null) // reading line-by-line
{
System.out.println(str);
try {
// Open given file in append mode.
BufferedWriter out = new BufferedWriter(
new FileWriter(filename, true));
out.write(str);
out.write("\n");
out.close();
}
catch (IOException e) {
System.out.println("exception occoured" + e);
}
}
socketRead.close();
}
catch(Exception e){
}
}
if(commands[0].equals(cmp10)){
try{
Socket s = new Socket(serverip,client_port);
DataInputStream dataInpStream = new DataInputStream(s.getInputStream());
DataOutputStream dataOutStream = new DataOutputStream(s.getOutputStream());
String namegrp = commands[1];
dataOutStream.writeUTF("List"+":" + commands[0] +":"+nameport+":"+namegrp+":"+"listdetail");
System.out.println("Request to List Group Details Sent");
String response ="";
response = dataInpStream.readUTF();
System.out.println(response);
dataOutStream.flush();
dataInpStream.close();
s.close();
}
catch(IOException ex)
{
System.out.println("Unable to List the group " + commands[1]);
}
}
if(commands[0].equals(cmp8)){
try{
Socket s = new Socket(serverip,client_port);
DataInputStream dataInpStream = new DataInputStream(s.getInputStream());
DataOutputStream dataOutStream = new DataOutputStream(s.getOutputStream());
String namegrp = commands[1];
dataOutStream.writeUTF("Join"+":" + commands[0] +":"+nameport+":"+namegrp+":"+"joingroup");
System.out.println("Request to join Group Sent");
String response ="";
response = dataInpStream.readUTF();
System.out.println(response);
dataOutStream.flush();
dataInpStream.close();
s.close();
}
catch(IOException ex)
{
System.out.println("Unable to Join the group " + commands[1]);
}
}
if(commands[0].equals(cmp9)){
try{
Socket s = new Socket(serverip,client_port);
DataInputStream dataInpStream = new DataInputStream(s.getInputStream());
DataOutputStream dataOutStream = new DataOutputStream(s.getOutputStream());
String namegrp = commands[1];
dataOutStream.writeUTF("Leave"+":" + commands[0] +":"+nameport+":"+namegrp+":"+"leavegroup");
System.out.println("Request to Leave Group Sent");
String response ="";
response = dataInpStream.readUTF();
System.out.println(response);
dataOutStream.flush();
dataInpStream.close();
s.close();
}
catch(IOException ex)
{
System.out.println("Unable to Leave the group " + commands[1]);
}
}
if(commands[0].equals(cmp6)){
try{
Socket s = new Socket(serverip,client_port);
DataInputStream dataInpStream = new DataInputStream(s.getInputStream());
DataOutputStream dataOutStream = new DataOutputStream(s.getOutputStream());
String namegrp = commands[1];
dataOutStream.writeUTF("create"+":" + commands[0] +":"+nameport+":"+namegrp+":"+"creategroup");
System.out.println("Create Group Completed");
String response ="";
response = dataInpStream.readUTF();
System.out.println(response);
dataOutStream.flush();
dataInpStream.close();
s.close();
}
catch(IOException ex)
{
System.out.println("Unable to Create the group " + commands[1]);
}
}
if(commands[0].equals(cmp5)){
try{
//to other pc //Connect
// Socket s= new Socket("10.1.34.33",client_port);
Socket s= new Socket(serverip,client_port);
DataInputStream dataInpStream=new DataInputStream(s.getInputStream());
DataOutputStream dataOutStream=new DataOutputStream(s.getOutputStream());
byte[] contents;
nameport = commands[1];
dataOutStream.writeUTF("create"+":" + commands[0] +":"+ourip+":"+nameport+":"+"createuser");
System.out.println("Create User Completed");
String response ="";
response = dataInpStream.readUTF();
System.out.println(response);
dataOutStream.flush();
dataInpStream.close();
s.close();
}
catch(IOException ex)
{
System.out.println("Unable to Create the User " + commands[1]);
}
}
if(commands[0].equals(cmp3)){
try{
//to other pc //Connect
// Socket s= new Socket("10.1.34.33",client_port);
// String IPaddr = "10.1.34.33";
Socket s= new Socket(serverip,client_port);
System.out.println(s.getLocalAddress().getHostAddress());
DataInputStream dataInpStream=new DataInputStream(s.getInputStream());
DataOutputStream dataOutStream=new DataOutputStream(s.getOutputStream());
byte[] contents;
dataOutStream.writeUTF(commands[0] +":"+commands[1]+":"+ ourip +":" + nameport +":"+ "create");
System.out.println("Directory Creation Completed");
dataOutStream.flush();
dataInpStream.close();
s.close();
}
catch(IOException ex)
{
System.out.println("Unable to create the directory " + commands[1]);
}
}
if(commands[0].equals(cmp1) || commands[0].equals(cmp2)){
//upload request
try{
File fileName = new File(commands[1]);
FileInputStream fileInpStream = new FileInputStream(fileName);
BufferedInputStream BuffInpStream = new BufferedInputStream(fileInpStream);
//Connect
Socket s= new Socket(serverip,client_port);
DataInputStream dataInpStream=new DataInputStream(s.getInputStream());
DataOutputStream dataOutStream=new DataOutputStream(s.getOutputStream());
byte[] contents;
long size = fileName.length(),sentSize=0;
dataOutStream.writeUTF(commands[0] +":" + String.valueOf(size)+":"+commands[1]+":"+ourip+":"+nameport+":"+ "uploaded");
if(commands[0].equals(cmp1)){
//TCP
while(sentSize!=size)
{
int window = 10000;
if(size - sentSize >= window)
sentSize += window;
else
{
window = (int)(size - sentSize);
sentSize+=window;
}
contents = new byte[window];
BuffInpStream.read(contents,0,window);
TrasferStatus(sentSize,size);
dataOutStream.write(contents);
}
System.out.println("File Transfer Completed");
dataOutStream.flush();
dataInpStream.close();
s.close();
}
else
{
//UDP.
//Closing the existing TCP socket.
dataOutStream.flush();
dataInpStream.close();
s.close();
//Creating the UDP socket and sending.
DatagramSocket udpSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(serverip);
// InetAddress IPAddress = InetAddress.getByName("localhost");
while(sentSize!=size)
{
int window = 10000;
if(size - sentSize >= window)
sentSize += window;
else
{
window = (int)(size - sentSize);
sentSize+=window;
}
contents = new byte[window];
BuffInpStream.read(contents,0,window);
TrasferStatus(sentSize,size);
DatagramPacket udpPacket = new DatagramPacket(contents,window, IPAddress, udp_client_port);
udpSocket.send(udpPacket);
}
contents = new String("UDPEND").getBytes();
DatagramPacket udpPacket = new DatagramPacket(contents,6, IPAddress, udp_client_port);
udpSocket.send(udpPacket);
udpSocket.close();
}
}
catch(FileNotFoundException ex)
{
System.out.println( commands[1] + " File not found.");
}
catch(IOException ex)
{
System.out.println("Unable to open the file " + commands[1]);
}
}
}
}
}
}
FileServer.java
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.*;
import java.io.*;
import java.util.*;
public class FileServer {
public static Vector<String> Group;
public static Map< String, Vector <String> > GroupUserList;
public static Map<String, Socket> clients = new HashMap<String, Socket>();
public static List<Socket> Sending = new ArrayList<Socket>();
public static void main(String[] args) {
ServerSocket ss = null;
DatagramSocket udp_ser = null;
int port = 3333,udp_ser_port=9000;
Group = new Vector<String>();
GroupUserList = new HashMap< String, Vector <String> >();
try{
ss = new ServerSocket(port);
udp_ser = new DatagramSocket(udp_ser_port);
}catch(IOException e){
e.printStackTrace();
}
while (true) {
Socket s =null;
try
{
s = ss.accept();
DataInputStream dataInpStream=new DataInputStream(s.getInputStream());
DataOutputStream dataOutStream = new DataOutputStream(s.getOutputStream());
System.out.println("New thread for client");
Thread t = new ClientHandler(s,dataInpStream,dataOutStream,udp_ser);
t.start();
}
catch(Exception r)
{
// s.close();
System.out.println("Socket timed out!");
r.printStackTrace();
break;
}
}
}
}
class ClientHandler extends Thread{
final DataInputStream dataInpStream;
final DataOutputStream dataOutStream;
final Socket s;
final DatagramSocket udp_ser;
public static String username;
public static String listdetailfile;
public ClientHandler(Socket s, DataInputStream dataInpStream, DataOutputStream dataOutStream, DatagramSocket udp_ser)
{
this.s = s;
this.dataInpStream = dataInpStream;
this.dataOutStream = dataOutStream;
this.udp_ser = udp_ser;
}
public static void RecieveStatus(long a, long b)
{
//Function to Print the Progress bar.
System.out.println("File Received : ");
int per =(int) ((a*100)/b);
System.out.printf("[");
for(int k=0;k<per/10;k++)
System.out.printf("=");
for(int k=per/10;k<10;k++)
System.out.printf(" ");
System.out.println("] " + String.valueOf(per) + "%");
}
public static void listFiles(String path)
{
File folder = new File(path);
File[] files = folder.listFiles();
for (File file : files)
{
if (file.isFile())
{
String tempfileloc = folder + "/" + file.getName();
// String[] tempfilelocs = tempfileloc.split(":");
// listdetailfile += file.getAbsolutePath() + "\n";
listdetailfile = listdetailfile + tempfileloc + "\n";
// System.out.println(file.getName());
}
else if (file.isDirectory())
{
listFiles(file.getPath());
}
}
}
public void run(){
while(true)
{
try{
//Reading the message from client.
String strRecv="";
// System.out.println("ikada dhaka ok ankunta");
try{
strRecv = dataInpStream.readUTF();
}
catch(Exception e){
// System.out.println("panicheyatle");
}
//Checking if it is a file transfer request.
String cmp1 = "upload",cmp2 = "uploadudp",cmp3="create",cmp4="move",cmp5 ="createuser",cmp6="creategroup",cmp7="listgroups";
String cmp8 = "joingroup",cmp9 = "leavegroup",cmp10 = "listdetail",cmp11 = "getfile",cmp12 ="sharemsg";
String[] Recv = strRecv.split(":");
for(int i= 0; i <=Recv.length-1; i++)
{System.out.println(Recv[i]);}
byte[] contents = new byte[1000];
BufferedOutputStream bufferOutStream=null;
// System.out.println(Recv.length);
if(Recv.length == 2){
if(Recv[0].equals(cmp12)){
String temprep ="shdhjfgjf";
for(Map.Entry<String, Vector<String> > entry : FileServer.GroupUserList.entrySet()){
Vector<String> userlist = new Vector<String> ();
userlist = entry.getValue();
temprep += userlist.size();
temprep = temprep + "\n" + "Username is :" + username + "\n";
if(userlist.contains(username)){
Iterator value = userlist.iterator();
while(value.hasNext()){
Object tempvalue = value.next();
FileServer.Sending.add(FileServer.clients.get(tempvalue));
temprep +=tempvalue;
temprep += "Yes\n";
temprep = temprep + "\n" + tempvalue + "Size is " + FileServer.Sending.size() + "\n";
}
}
}
String out = username +"-->";
// FileServer.Sending.remove(this.s);
out += Recv[1];
temprep += "\n this is final and size is " + FileServer.Sending.size() + " \n";
dataOutStream.writeUTF(temprep);
try{
// Thread t1 = new MsgHandler(out, FileServer.Sending);
// t1.start();
}catch(Exception e){
}
}
}
if(Recv.length == 4){
if(Recv[3].equals(cmp7)){
String sendresponse = "";
Iterator grp = FileServer.Group.iterator();
while (grp.hasNext()) {
sendresponse += grp.next();
sendresponse += " ";
}
dataOutStream.writeUTF(sendresponse);
}
}
if(Recv.length == 5){
if(Recv[4].equals(cmp3)){
// System.out.println("sdgksadknldsfnb");
String temp="";
temp = "./" +Recv[3]+"/" + Recv[1];
File folder = new File(temp);
folder.mkdirs();
}
if(Recv[4].equals(cmp5)){
String temp="";
temp = "./" +Recv[3];
File folder = new File(temp);
folder.mkdirs();
username = Recv[3];
FileServer.clients.put(Recv[3],this.s);
int tempolen = FileServer.clients.size();
dataOutStream.writeUTF("As per your request User is created"+tempolen);
}
if(Recv[4].equals(cmp6)){
FileServer.Group.add(Recv[3]);
// Vector <String> single = new Vector<String> ();
// single.add(Recv[2]);
// FileServer.GroupUserList.put(Recv[3],single);
dataOutStream.writeUTF("As per your request new group is created with name "+ Recv[3] + "\nNow the groups length is: " +FileServer.Group.size() + " \n Join the group to add yourself into it");
}
if(Recv[4].equals(cmp8)){
if(FileServer.GroupUserList.containsKey(Recv[3])){
Vector <String> Listgrp = FileServer.GroupUserList.get(Recv[3]);
if(Listgrp.contains(Recv[2])){
dataOutStream.writeUTF("You are already there in this group please try a new one");
}
else{
Listgrp.add(Recv[2]);
FileServer.GroupUserList.put(Recv[3],Listgrp);
dataOutStream.writeUTF("Now the length of "+ Recv[3] +" after you joined is:" +Listgrp.size());
}
}
else{
Vector <String> single = new Vector<String> ();
single.add(Recv[2]);
FileServer.GroupUserList.put(Recv[3],single);
dataOutStream.writeUTF("Now the length of "+ Recv[3] +" after you joined is:" +single.size());
}
}
if(Recv[4].equals(cmp9)){
if(FileServer.GroupUserList.containsKey(Recv[3])){
Vector <String> Listgrp = FileServer.GroupUserList.get(Recv[3]);
if(Listgrp.size() >= 1){
Listgrp.remove(Recv[2]);
FileServer.GroupUserList.put(Recv[3],Listgrp);
dataOutStream.writeUTF("Now the length of "+ Recv[3] +" after you left is:" +Listgrp.size());
}
else{
dataOutStream.writeUTF("You are not there in the group Please check the group name");
}
}
else{
dataOutStream.writeUTF("You are not there in the group Please check the group name");
}
}
if(Recv[4].equals(cmp10)){
if(FileServer.GroupUserList.containsKey(Recv[3])){
Vector <String> Listgrp = FileServer.GroupUserList.get(Recv[3]);
if(Listgrp.size() >= 1){
if(Listgrp.contains(Recv[2])){
String response ="";
Iterator usernameingrp = Listgrp.iterator();
while (usernameingrp.hasNext()) {
String usrname = "./";
response += "Files under the user : \n";
usrname += usernameingrp.next();
String tmpusr = usrname.substring(2,usrname.length());
response += tmpusr;
response += "\n ================================= \n";
listFiles(usrname);
response += listdetailfile;
listdetailfile = "";
// File folder = new File(usrname);
// File[] files = folder.listFiles();
// for (File file : files)
// {
// if (file.isFile())
// {
// response += file.getPath();
// response += "\n";
// }
// }
}
dataOutStream.writeUTF(response);
}
else{
dataOutStream.writeUTF("You are not there in the group Please check the group name");
}
}
else{
dataOutStream.writeUTF("You are not there in the group Please check the group name");
}
}
else{
dataOutStream.writeUTF("You are not there in the group Please check the group name");
}
}
if(Recv[4].equals(cmp11)){
String fname ="./";
String Path[] = Recv[3].split("/");
for(int i=1;i<Path.length-1;i++){
fname += Path[i];
fname += "/";
}
fname += Path[Path.length -1];
// reading file contents
BufferedReader contentRead = new BufferedReader(new FileReader(fname) );
// keeping output stream ready to send the contents
OutputStream ostream = this.s.getOutputStream( );
PrintWriter pwrite = new PrintWriter(ostream, true);
String str;
while((str = contentRead.readLine()) != null) // reading line-by-line from file
{
pwrite.println(str); // sending each line to client
}
this.s.close(); // closing network sockets
pwrite.close(); contentRead.close();
}
}
if(Recv.length==7){
if(Recv[6].equals(cmp4)){
String src="",dest="";
src = "./"+Recv[5]+Recv[2].substring(1);
dest = "./"+Recv[5]+Recv[3].substring(1);
// System.out.println(src);
// System.out.println(dest);
File a = new File(src);
a.renameTo(new File(dest + a.getName()));
a.delete();
}
}
if(Recv.length==6){
//File Transfer.
int fileSize = Integer.parseInt(Recv[1]),rec=0,bread;
try{
//Creating the file and opening bufferreader.
String fileLocationdir ="./"+Recv[4];
System.out.println(fileLocationdir);
File tt = new File(fileLocationdir,Recv[2]);
tt.createNewFile();
FileOutputStream fos = new FileOutputStream(tt);
bufferOutStream = new BufferedOutputStream(fos);
} catch (IOException e) {
System.out.println("Error Creating and writing to file.");
e.printStackTrace();
}
if(Recv[0].equals(cmp1))
{
//TCP
while( (bread=this.dataInpStream.read(contents) ) !=-1)
{
bufferOutStream.write(contents, 0, bread);
rec += bread;
RecieveStatus(rec,fileSize);
}
this.s.close();
}
else
{
//UDP.
//Closing the already open TCP socket and recieveing packets.
this.s.close();
// System.out.println("sdkvksdjfkvbhefdk");
while(rec!=fileSize)
{
DatagramPacket dp=new DatagramPacket(contents,contents.length);
this.udp_ser.receive(dp);
bread = dp.getLength();
rec += bread;
bufferOutStream.write(contents, 0, bread);
RecieveStatus(rec,fileSize);
String ram = new String("UDPEND"),ll = new String(contents);
if( ram.equals(ll) )
break;
}
}
bufferOutStream.flush();
System.out.println("File Receiving Completed");
System.out.printf("$>>");
}
}
catch(IOException e){
e.printStackTrace();
System.out.println("Socket timed out!");
break;
}
}
try{
this.dataInpStream.close();
this.dataOutStream.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
class MsgHandler extends Thread
{
String message;
List<Socket> receiver_list = new ArrayList<Socket>();
public MsgHandler(String message, List<Socket> receiver_list)
{
this.message = message;
this.receiver_list = receiver_list;
}
@Override
public void run()
{
// String[] split_msg = this.message.split(" ");
// if(split_msg[0].equals("file"))
// {
// System.out.println(this.message);
for(int i=0;i < this.receiver_list.size(); ++i){
Socket recv = this.receiver_list.get(i);
try{
DataOutputStream dos = new DataOutputStream(recv.getOutputStream());
dos.writeUTF(this.message);
System.out.println("Message pamputhunam");
}
catch (IOException e) {
// e.printStackTrace();
}
}
}
}
Please comment in case if you didn't understand any part
Get Answers For Free
Most questions answered within 1 hours.