Skip to content

Instantly share code, notes, and snippets.

@letanloc1998
Created November 1, 2019 04:25
Show Gist options
  • Save letanloc1998/6564135633c4ce84aa9bb6ec4131b03b to your computer and use it in GitHub Desktop.
Save letanloc1998/6564135633c4ce84aa9bb6ec4131b03b to your computer and use it in GitHub Desktop.
/*
* Le Tan Loc B1605339
*/
package Client;
import java.awt.Desktop;
import java.awt.FileDialog;
import java.io.*;
import java.net.*;
import java.util.Date;
import java.util.Scanner;
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;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Client {
public static ClientChatThread clientChatThread;
public static ClientFileThread clientFileThread;
public static Main_Jframe mainJframe;
//public final static int FILE_SIZE = 102400000;
//public final static String FILE_TO_SEND = System.getProperty("user.home") + "\\Desktop\\locb1605339.txt";
public static void main(String[] args) {
mainJframe = new Main_Jframe();
mainJframe.setVisible(true);
// Địa chỉ máy chủ.
//final String ipServer = "localhost";
final String ipServer = "192.168.214.132";
Socket socketChatClient = null;
Socket socketFileClient = null;
BufferedWriter os = null;
BufferedReader is = null;
try {
// Gửi yêu cầu kết nối tới Server đang lắng nghe trên máy có ip là ipSerever cổng 7777.
socketChatClient = new Socket(ipServer, 9999); //socket to chat
socketFileClient = new Socket(ipServer, 9998);
// Tạo luồng đầu ra tại client (Gửi dữ liệu tới server)
os = new BufferedWriter(new OutputStreamWriter(socketChatClient.getOutputStream()));
// Luồng đầu vào tại Client (Nhận dữ liệu từ server).
is = new BufferedReader(new InputStreamReader(socketChatClient.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + ipServer);
return;
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " + ipServer);
return;
}
clientChatThread = new ClientChatThread(socketChatClient, os, is);
clientChatThread.start();
clientFileThread = new ClientFileThread(socketFileClient);
clientFileThread.start();
//Đóng các luồng
//os.close();
//is.close();
//socketOfClient.close();
}
public static String GetFilePath() {
FileDialog fd = new FileDialog(new JFrame());
fd.setVisible(true);
File[] f = fd.getFiles();
if (f.length > 0) {
System.out.println(fd.getFiles()[0].getAbsolutePath());
return fd.getFiles()[0].getAbsolutePath();
}
return null;
}
public static void openFile(String filePath){
File file = new File(filePath);
//first check if Desktop is supported by Platform or not
if(!Desktop.isDesktopSupported()){
System.out.println("Desktop is not supported");
return;
}
Desktop desktop = Desktop.getDesktop();
if(file.exists()) try {
desktop.open(file);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static class ClientChatThread extends Thread {
private Socket socketChatClient = null;
private BufferedWriter os = null;
private BufferedReader is = null;
public ClientChatThread(Socket socketChatClient, BufferedWriter os, BufferedReader is) {
this.socketChatClient = socketChatClient;
this.os = os;
this.is = is;
}
public void send(String chat) {
try {
os.write(chat); // Ghi dữ liệu vào luồng đầu ra của Socket tại Client.
os.newLine(); // kết thúc dòng
os.flush(); // đẩy dữ liệu đi.
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void run() {
try {
while (true) {
String responseLine;
while ((responseLine = is.readLine()) != null) {
System.out.println("Server1: " + responseLine);
mainJframe.addChatListView(responseLine);
if (responseLine.indexOf("OK") != -1) {
break;
}
}
}
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
public static class ClientFileThread extends Thread {
private Socket socketFileClient;
public ClientFileThread(Socket socketFileClient) {
this.socketFileClient = socketFileClient;
}
public void send(String filePath) throws InterruptedException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
File myFile = new File(filePath);
BufferedWriter osBw = null;
try {
osBw = new BufferedWriter(new OutputStreamWriter(socketFileClient.getOutputStream()));
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
try {
osBw.write(myFile.getName()); // Ghi dữ liệu vào luồng đầu ra của Socket tại Client.
osBw.newLine(); // kết thúc dòng
osBw.flush(); // đẩy dữ liệu đi.
osBw.write((int) myFile.length()+""); // Ghi dữ liệu vào luồng đầu ra của Socket tại Client.
osBw.newLine(); // kết thúc dòng
osBw.flush(); // đẩy dữ liệu đi.
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
Boolean sendFile = true;
while(sendFile){
try {
// send file
byte[] mybytearray = new byte[(int) myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
for (int i = 0; i < 7; i++) {
System.out.println("String " + i + " : " + mybytearray[i]);
}
os = socketFileClient.getOutputStream();
TimeUnit.SECONDS.sleep(2);
os.write(mybytearray, 0, mybytearray.length);
/*for (int i = 0; i < 7; i++) {
System.out.println("String " + i + " : " + mybytearray[i]);
}*/
os.flush();
System.out.println("Send " + filePath + "(" + mybytearray.length + " bytes)");
System.out.print("Done");
sendFile = false;
//code quan trọng, không thể xóa locb1605339 (đóng luồng)
try {
if (bis != null) {
bis.close();
}
/*if (os != null) {
os.close();
}*/
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@Override
public void run() {
BufferedReader isBr = null;
try {
isBr = new BufferedReader(new InputStreamReader(socketFileClient.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
while (true) {
try {
//lắng nghe file gửi về
String fileClientName = null;
while ((fileClientName = isBr.readLine()) != null) {
try {
System.out.println("Connecting...");
int fileSize = Integer.parseInt(isBr.readLine());
int bytesRead;
//int current = 0; //dung luong file thuc te
FileOutputStream fos = null;
BufferedOutputStream bos = null;
//locb1605339 Get file name
String filePath = System.getProperty("user.home") + "\\Desktop\\" + new Date().getTime() + fileClientName;
System.out.println("filePath: " + filePath);
// receive file
byte[] mybytearray = new byte[fileSize]; //Read file in there
InputStream is = socketFileClient.getInputStream();
System.out.println("bug 7");
fos = new FileOutputStream(filePath);
bos = new BufferedOutputStream(fos); //Create Buffer (Create file with no data)
System.out.println("bug 8");
//bytesRead = is.read(mybytearray, 0, mybytearray.length);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
System.out.println("size " + fileSize + " length " + 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); //Write data into file
bos.write(mybytearray, 0, fileSize); //Write data into file
bos.flush(); //Write data to file
System.out.println("String" + mybytearray[0]);
System.out.println("String" + mybytearray[(int) fileSize - 1]);
System.out.println("String" + mybytearray[(int) fileSize - 2]);
for (int i = 0; i < 10; i++) {
System.out.println("String " + i + " : " + mybytearray[i]);
}
Client.openFile(filePath);
System.out.println("File " + filePath + " downloaded (" + fileSize + " bytes read)");
try {
if (fos != null) {
fos.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
//Le Tan Loc B1605339
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment