3 Replies - 2457 Views - Last Post: 27 October 2015 - 08:32 AM Rate Topic: -----

#1 garukb1   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 19-October 15

Transfer File in a simple chat

Posted 27 October 2015 - 06:28 AM

Hi everybody, Im a beginner, I have found a very good tutorial for a chat application here My link and Im trying to learn it. I want to transfer file from client - client so I create another Thread and it starts with ClientThread at the same time to wait to read File from Client but it doesn't work this way.

Then I tried to read the object Message as usual first as if the type is set for "receive file" then server will read file but it doesn't work as well
public class Server {
	
	private static int uniqueID;
	private SimpleDateFormat sdf;
	private ArrayList<ClientThread> list;
	private int port;
	private boolean t;
	
	public Server(int port){
		this.port = port;
		sdf = new SimpleDateFormat("HH:mm:ss");
		list = new ArrayList<ClientThread>();
	}
	
	public void start(){
		t = true;
		ServerSocket server;
		try{
			server = new ServerSocket(port);
			while(t){
				System.out.println("Server Đă sẵn sàng cho Client Port : " + port + ".");
				Socket socket = server.accept();
				if(!t)
					break;
				ClientThread t = new ClientThread(socket);
				list.add(t);
				t.start();
				
				
				
				//thử
				FileThread ft = new FileThread(socket);
				ft.run();
			}
			try{
				server.close();
				for(int i = 0; i < list.size(); i++){
					ClientThread ct = list.get(i);
					ct.socket.close();
					ct.oos.close();
					ct.ois.close();
				}
			}
			catch(Exception e){
				System.out.println("Lỗi khi đóng Server và  Client: " + e);
				}
		}
		catch(Exception e){
			System.out.println(sdf.format(new Date()) + "Lỗi ServerSocket: " + e);
		}
			
	}
	
	//Hien Thi tren Server va gui cho tung user
	 private synchronized void broadcast(String msg) {
		 String time = sdf.format(new Date());
		 String message = time + " " + msg + "\n";
		 System.out.println(message);
		 for(int i = 0; i <list.size(); i++){
			 ClientThread ct = list.get(i);
			 if(!ct.writeMessage(message) ){
				 list.remove(i);
				 System.out.println("Không thể gửi tin cho Client tên" + ct.username + " Client đă ngắt kết nối");
			 }
		 }
		 
		  }

	/* private synchronized void sendFileAll(byte[] mybytearray1) {
		  for(int i = list.size(); --i > 0;) {
			  ClientThread ct = list.get(i);
			  if(!ct.sendFile(mybytearray1)) {
				  list.remove(i);
				  }
			  }
		  }*/
	 
	
	
	 class ClientThread extends Thread {
		 Socket socket;
		 ObjectInputStream ois;
		 ObjectOutputStream oos;
		 int id;
		 String username;
		 Message msg;
		 String date;
		 
		 //Phan Doc File
		 OutputStream os;
		 InputStream is;
		 BufferedInputStream bis;
		 byte[] mybytearray = new byte[1024];
		  
		  ClientThread(Socket socket) {
			  id = ++uniqueID;
			  this.socket = socket;
			    try
			    {
			    	//bis = new BufferedInputStream(new FileInputStream(new File("")));
			    	oos = new ObjectOutputStream(socket.getOutputStream());
			    	ois  = new ObjectInputStream(socket.getInputStream());
			    	username = (String) ois.readObject();
			    	System.out.println(username + "Đă kết nối");

			    }
			    catch (IOException e) {
			    	 System.out.println(e.getMessage());
			    	      return;
			    }
			    catch (ClassNotFoundException e) {
			    }
			    
			    date = new Date().toString() + "\n";
		  }
		  
		  //Lap nhan Object Message tu Client
		  public void run(){
			boolean t = true;
			while(t){
				try {
					msg = (Message) ois.readObject();
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				String message = msg.getMessage();
				
				int number = msg.getType();
				
				if(number == 1)
					broadcast(username + ": " + message);	
				else if(number == 2){
					//nhan File neu co
					/*try {
						is = socket.getInputStream();
						int size = is.read(mybytearray, 0 , mybytearray.length);
						System.out.println("File da len server");
						broadcast("File.txt");
						sendFileAll(mybytearray);
						is.close();
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						System.out.println("error");
						}*/
					
					
					//Test
					//FileThread ft = new FileThread(socket);
					//ft.run();
					}
				}
			}
		  private boolean sendFile(byte[] mybytearray1){
			  if(!socket.isConnected()) {
				   close();
				   return false;
			   }
			  try {
				os = socket.getOutputStream();
				os.write(mybytearray1,0,mybytearray1.length);  
				os.flush();
				os.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			  return true;
		  }
		  
		  //gui Message String cho user
		  private boolean writeMessage(String msg) {
			   if(!socket.isConnected()) {
				   close();
				   return false;
			   }
			   try {
				   oos.writeObject(msg);
			   }
			   catch(IOException e) {
				   System.out.println(e.getMessage());
			   }
			   return true;
		   }
		  
		  private void close(){
			  try {
				  if(oos != null)
					  oos.close();
				  if(ois != null)
					  ois.close();
				  if(socket != null)
					  socket.close();
				   }
			  catch(Exception e) {}
		}
		  
	 }
	 
	 class FileThread implements Runnable{
		 Socket socket;
		 OutputStream os;
		 InputStream is;
		 BufferedInputStream bis;
		 byte[] mybytearray = new byte[1024];
		 
		 FileThread(Socket socket){
			 this.socket = socket;
		 }
		 

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				is = socket.getInputStream();
				int size = is.read(mybytearray, 0 , mybytearray.length);
				System.out.println("File da len server");
				/*broadcast("File.txt");
				sendFileAll(mybytearray);*/
				is.close();
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.println("Lỗi đọc File Server");
				}
			}
		}
		 
	 
	 
	 public static void main(String[] args) {
		Server server = new Server(6789);
		server.start();
	}
	 


I know that I was so wrong to try to recieve file this way as this is the way that I understood and tried to develope.
I heard that we can make another socket connection for transfering file and then can chat at the time but I have no idea how to do it. Hope you guys can help me to solve this. Thanks so much.

Is This A Good Question/Topic? 0
  • +

Replies To: Transfer File in a simple chat

#2 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 793
  • View blog
  • Posts: 6,005
  • Joined: 25-December 13

Re: Transfer File in a simple chat

Posted 27 October 2015 - 06:34 AM

Can you post the client code so the system can be compiled and tested?

Also describe the steps that the user does to execute the program.

Pleaae add the import statements that the code needs to compile.

This post has been edited by NormR: 27 October 2015 - 06:37 AM

Was This Post Helpful? 0
  • +
  • -

#3 garukb1   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 19-October 15

Re: Transfer File in a simple chat

Posted 27 October 2015 - 07:54 AM

View PostNormR, on 27 October 2015 - 06:34 AM, said:

Can you post the client code so the system can be compiled and tested?

Also describe the steps that the user does to execute the program.

Pleaae add the import statements that the code needs to compile.


This is Server
package Server;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import Message.Message;

public class Server {
	
	private static int uniqueID;
	private SimpleDateFormat sdf;
	private ArrayList<ClientThread> list;
	private int port;
	private boolean t;
	
	public Server(int port){
		this.port = port;
		sdf = new SimpleDateFormat("HH:mm:ss");
		list = new ArrayList<ClientThread>();
	}
	
	public void start(){
		t = true;
		ServerSocket server;
		try{
			server = new ServerSocket(port);
			while(t){
				System.out.println("Server is waiting for Clients on Port " + port + ".");
				Socket socket = server.accept();
				if(!t)
					break;
				ClientThread t = new ClientThread(socket);
				list.add(t);
				t.start();
				
				
				
				//It doesn't work when I start another Thread
				/*FileThread ft = new FileThread(socket);
				ft.run();*/
			}
			try{
				server.close();
				for(int i = 0; i < list.size(); i++){
					ClientThread ct = list.get(i);
					ct.socket.close();
					ct.oos.close();
					ct.ois.close();
				}
			}
			catch(Exception e){
				System.out.println("Lỗi khi đóng Server và  Client: " + e);
				}
		}
		catch(Exception e){
			System.out.println(sdf.format(new Date()) + "Lỗi ServerSocket: " + e);
		}
			
	}
	

	 private synchronized void broadcast(String msg) {
		 String time = sdf.format(new Date());
		 String message = time + " " + msg + "\n";
		 System.out.println(message);
		 for(int i = 0; i <list.size(); i++){
			 ClientThread ct = list.get(i);
			 if(!ct.writeMessage(message) ){
				 list.remove(i);
				 System.out.println("Không thể gửi tin cho Client tên" + ct.username + " Client đă ngắt kết nối");
			 }
		 }
		 
		  }
	/* private synchronized void sendFileAll(byte[] mybytearray1) {
		  for(int i = list.size(); --i > 0;) {
			  ClientThread ct = list.get(i);
			  if(!ct.sendFile(mybytearray1)) {
				  list.remove(i);
				  }
			  }
		  }*/
	 
	
	
	 class ClientThread extends Thread {
		 Socket socket;
		 ObjectInputStream ois;
		 ObjectOutputStream oos;
		 int id;
		 String username;
		 Message msg;
		 String date;
		 
		 
		 OutputStream os;
		 InputStream is;
		 BufferedInputStream bis;
		 byte[] mybytearray = new byte[1024];
		  
		  ClientThread(Socket socket) {
			  id = ++uniqueID;
			  this.socket = socket;
			    try
			    {
			    	
			    	oos = new ObjectOutputStream(socket.getOutputStream());
			    	ois  = new ObjectInputStream(socket.getInputStream());
			    	username = (String) ois.readObject();
			    	System.out.println(username + "Đă kết nối");

			    }
			    catch (IOException e) {
			    	 System.out.println(e.getMessage());
			    	      return;
			    }
			    catch (ClassNotFoundException e) {
			    }
			    
			    date = new Date().toString() + "\n";
		  }
		  
		 
		  public void run(){
			boolean t = true;
			while(t){
				try {
					msg = (Message) ois.readObject();
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				String message = msg.getMessage();
				
				int number = msg.getType();
				
				//print and send message to Client
				if(number == 1)
					broadcast(username + ": " + message);
				
				// I tried to receive File if type = 2
				else if(number == 2){
					
					try {
						is = socket.getInputStream();
						int size = is.read(mybytearray, 0 , mybytearray.length);
						System.out.println("Server received a File");
						//sendFileAll(mybytearray);
						is.close();
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						System.out.println("Can't read file");
						}
					
				
					}
				}
			}
		  
		  /*private boolean sendFile(byte[] mybytearray1){
			  if(!socket.isConnected()) {
				   close();
				   return false;
			   }
			  try {
				os = socket.getOutputStream();
				os.write(mybytearray1,0,mybytearray1.length);  
				os.flush();
				os.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			  return true;
		  }*/
		  
		 
		  private boolean writeMessage(String msg) {
			   if(!socket.isConnected()) {
				   close();
				   return false;
			   }
			   try {
				   oos.writeObject(msg);
			   }
			   catch(IOException e) {
				   System.out.println(e.getMessage());
			   }
			   return true;
		   }
		  
		  private void close(){
			  try {
				  if(oos != null)
					  oos.close();
				  if(ois != null)
					  ois.close();
				  if(socket != null)
					  socket.close();
				   }
			  catch(Exception e) {}
		}
		  
	 }
	 
	 //This is a new Thread I made to receive File hopefully
	 class FileThread implements Runnable{
		 Socket socket;
		 OutputStream os;
		 InputStream is;
		 BufferedInputStream bis;
		 byte[] mybytearray = new byte[1024];
		 
		 FileThread(Socket socket){
			 this.socket = socket;
		 }
		 

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				is = socket.getInputStream();
				int size = is.read(mybytearray, 0 , mybytearray.length);
				System.out.println("Server received a File");
				is.close();
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.println("Can't read File");
				}
			}
		}
		 
	 
	 
	 public static void main(String[] args) {
		Server server = new Server(6789);
		server.start();
	}
	 

}




Message Object
package Message;

import java.io.Serializable;

public class Message implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private int type;
	private String message;
	
	public Message(int type, String message) {
		this.type = type;
		this.message = message;
	}
	public int getType() {
		return type;
	}
	public void setType(int type) {
		this.type = type;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
}



Client
package Client;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import Message.Message;

public class Client {
	private ObjectOutputStream oos;
	private ObjectInputStream ois;
	private Socket socket;
	private int port;
	private String username, server;
	String filename;
	File myfile;
	byte[] mybytearray; 
	OutputStream os;
	BufferedInputStream bis;
	
	
	public Client(String server, int port, String username){
		this.server = server;
		this.port = port;
		this.username = username;
	}
	
	public boolean start(){
		
		try {
			socket = new Socket(server,port);
			oos = new ObjectOutputStream(socket.getOutputStream());
			ois = new ObjectInputStream(socket.getInputStream());
			
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			System.out.println("error" + e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Connected to Server " + socket.getPort());
		new ListenFromServer().start();
		try {
			oos.writeObject(username);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			disconnected();
			return false;
		}
		return true;
		
	}
	
	void disconnected(){
			try {
				if (socket != null)
					socket.close();
				if (ois != null)
					ois.close();
				if (oos != null)
					oos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	public void sendMessage(Message msg){
		try {
			oos.writeObject(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void sendFile(String name){
		filename = name;
		try {
			myfile = new File(filename);
			os = socket.getOutputStream();
			mybytearray = new byte[(int) myfile.length()];
			bis = new BufferedInputStream(new FileInputStream(myfile));
			bis.read(mybytearray, 0 , mybytearray.length);
			os.write(mybytearray, 0, mybytearray.length);
			os.flush();
			System.out.println(username + " Đă gửi File");
			os.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("Can not send File");
		}
	}
	
	//Lap Nhan String message
	class ListenFromServer extends Thread{
		public void run(){
			while(true){
					try {
						String msg = (String) ois.readObject();
						System.out.println(msg);
						System.out.print("\n");
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
				// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}	
			}
	}
	public static void main(String[] args) {
		// Message message has type == 1 it means sending string message if type == 2 means I try to send a File hopefully
		Client client = new Client("localhost",6789,"UserA");
		client.start();
		Scanner sc = new Scanner(System.in);
		while(true){
			System.out.println("<");
			String msg = sc.nextLine();
			Message msgsend;
			if(msg.equalsIgnoreCase("SENDFILE")) {
				System.out.println("Please enter File name");
				String filename = sc.nextLine();
				msgsend = new Message(2, filename);
				client.sendMessage(msgsend);
				client.sendFile(filename);
			}
			else
			{
				msgsend = new Message(1, msg);
				client.sendMessage(msgsend);
			}
		}
		
	}

}



if Client type words It will send Object Message to Server with type == 1 and Client will receive a string message
if Client type SENDFILE and then type file name It will send a Object Message to Client type == 2 and I'm trying to receive that file on Server.
pardon me for my codes and English.
Thank you.
Was This Post Helpful? 0
  • +
  • -

#4 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 793
  • View blog
  • Posts: 6,005
  • Joined: 25-December 13

Re: Transfer File in a simple chat

Posted 27 October 2015 - 08:32 AM

Quote

I'm trying to receive that file on Server

What happens? Are there any error messages?

What happens in the server after it reads some bytes in the run() method?

This post has been edited by NormR: 27 October 2015 - 08:51 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1