Tài liệu học tập Lập trình mạng

A. MỤC TIÊU

Trang bị cho sinh viên kỹ năng lập trình cơ bản trong java: cấu trúc if, vòng lặp while do,

for., khai báo mảng, xử lý trên mảng.

B. NỘI DUNG

- Lệnh rẽ nhánh (if), lệnh lựa chọn (switch).

- Lệnh lặp, sử dụng mảng để thao tác trên các phần tử cùng kiểu.

C. YÊU CẦU PHẦN CỨNG, PHẦN MỀM

- Máy tính cài HĐH windows, RAM tối thiểu 256MB.

- Phần mềm NETBEAN IDE 8.0, JDK 1.8.

D. KẾT QUẢ SAU KHI HOÀN THÀNH

Sinh viên thành thạo các câu lệnh : rẽ nhánh, lựa chọn, lệnh lặp, thao tác trên mảng, áp

dụng giải các bài tập từ đơn giản đến phức tạp.

E. HƯỚNG DẪN CHI TIẾT

1. Cấu trúc rẽ nhánh if else

Bài 2. Giải phương trình bậc 2 ax2 + bx + c = 0

Hướng dẫn:

Sử dụng Scanner nhập 3 số nguyên.a, b, c. Tính delta=b*b-4*a*c.

Sử dụng if kiểm tra từng trường hợp của delta.

Bài 3. Viết chương trình java cho phép tạo và thực hiện theo menu sau:

1. Nhập vào một số nguyên dương n.

2. Tính tổng các số từ 1 đến n

3. Kiểm tra n có là số nguyên tố

4. Kiểm tra n có là số hoàn hảo.

5. Hiển thị số n thành tích các thừa số nguyên tố.

6. Thoát

if(delta<>

System.out.println("PT vo nghiem");

else if(delta==0){

float x = (float)-b/(2*a);

System.out.printf("PT co nghiem kep x1=x2=%.2f",x);

}else{

float x1 = (float) (-b-Math.sqrt(delta))/(2*a);

float x2 = (float) (-b+Math.sqrt(delta))/(2*a);

}13

(Hiển thị 1 số nguyên dương thành tích các thừa số nguyên tố: n = 24 in ra: n = 23 x3)

Hướng dẫn:

Phương thức nhập: Dùng Scanner

Phương thức kiểm tra hoàn hảo

Tài liệu học tập Lập trình mạng trang 1

Trang 1

Tài liệu học tập Lập trình mạng trang 2

Trang 2

Tài liệu học tập Lập trình mạng trang 3

Trang 3

Tài liệu học tập Lập trình mạng trang 4

Trang 4

Tài liệu học tập Lập trình mạng trang 5

Trang 5

Tài liệu học tập Lập trình mạng trang 6

Trang 6

Tài liệu học tập Lập trình mạng trang 7

Trang 7

Tài liệu học tập Lập trình mạng trang 8

Trang 8

Tài liệu học tập Lập trình mạng trang 9

Trang 9

Tài liệu học tập Lập trình mạng trang 10

Trang 10

Tải về để xem bản đầy đủ

pdf 254 trang xuanhieu 8181
Bạn đang xem 10 trang mẫu của tài liệu "Tài liệu học tập Lập trình mạng", để tải tài liệu gốc về máy hãy click vào nút Download ở trên

Tóm tắt nội dung tài liệu: Tài liệu học tập Lập trình mạng

Tài liệu học tập Lập trình mạng
RMILoginClientView hiển thị bằng phương thức showMessage() 
7. Lớp RMILoginClientView hiển thị kết quả đăng nhập lên cho người dùng 
Sinh viên vận dụng các kiến thức đã học về lập trình RMI và kết nối cơ sở dữ liệu tiến 
hành viết các lớp tương ứng. 
Bài 5. Tổng hợp. Kết hợp kiến thức về RMI, database. Xây dựng hệ thống giao dịch ngân 
hàng phân tán. 
Phía Server Bấm button Connect: Server kết nối với RMI. 
Phía người dùng thực hiện những chức năng sau: 
Bài toán phát triển hệ thống ngân hàng phân tán đặt ra như sau: 
▪ Cơ sở dữ liệu được lưu trữ và quản lí trên Server, trong đó có 3 bảng: 
Bảng Account lưu thông tin tài khoản gồm hai trường IDaccount va Balance 
241 
Bảng AccountCustomer lưu thông tin tài khoản khách hàng gồm 2 trường idAccount 
và IdCustomer 
Bảng Customer lưu thông tin như sau 
▪ Chương trình phía Client hiện giao diện đồ họa, trong đó có ô text để nhập 
CustomerID và AccountID, và một nút QueryDatabase. 
▪ Khi nút QueryDatabase được click, chương trình Client sẽ gửi thông tin đăng nhập 
trên form giao diện, và gửi sang Server 
▪ Tại phía Server, mỗi khi nhận được thông tin gửi từ Client, sẽ tiến hành kiểm tra trong 
cơ sở dữ liệu xem có tài khoản nào trùng với thông tin nhận được hay không. 
▪ Phía Client, sau khi nhận được kết quả từ Server, sẽ hiển thị thông báo tương ứng 
Sau đó người dùng thực hiện các chức năng gửi tiền và rút tiền từ xa. 
Hướng dẫn: 
 Bước 1: Tạo Interface Account 
public interface Account extends Remote 
{ 
 //Trả về ngân hàng quản lý tài khoản này 
242 
 public BankManager getBankManager() throws RemoteException; 
 //Trả về Client của tài khoản này 
 public Client getClient() throws RemoteException; 
 //Lấy số dư tài khoản 
 public float getBalance() throws RemoteException; 
 //Chỉnh sửa số dư tài khoản 
 public void setBalance(float bal) throws RemoteException; 
 //phương thức rút tiền có kiểm tra số dư trước khi rút. Trả về amount 
 public long getCash (long amount) throws NoCashAvailableException, 
RemoteException; 
 //gửi tiền 
 public void deposit(float amount) throws RemoteException; 
 //rút tiền 
 public void withdraw(float amount) throws RemoteException; 
} 
 Bước 2: Tạo class AccountImpl thực hiện interface Account 
public class AccountImpl implements Account, Serializable 
{ 
 private BankManager bankManager; 
 private Client Client; 
 private float balance; 
 private String accountNumber; 
 public AccountImpl (BankManager bankManager, Client Client, String 
accountNumber, float bal) 
 { 
 this.bankManager = bankManager; 
 this.Client = Client; 
 this.balance = bal; 
 this.accountNumber = accountNumber; 
 } 
 public void deposit(float amount) 
 { 
 balance += amount; 
 } 
243 
 public void withdraw(float amount) 
 { 
 balance -= amount; 
 } 
 public BankManager getBankManager() throws RemoteException 
 { 
 return bankManager; 
 } 
public Client getClient() throws RemoteException 
 { 
 return Client; 
 } 
public float getBalance() throws RemoteException 
 { 
 return balance; 
 } 
public void setBalance(float bal) throws RemoteException 
 { 
 balance = bal; 
 } 
public long getCash(long amount) throws NoCashAvailableException, 
RemoteException 
 { 
 if (amount > balance) 
 { 
 throw new NoCashAvailableException(); 
 } 
 balance = balance - amount; 
 return amount; 
 } 
244 
} 
 Bước 3: Tạo interface BankManager 
public interface BankManager extends Remote 
{ 
 //Phương thức lấy tài khoản theo mã 
 public Account getAccount(String accountNumber) throws RemoteException; 
 //Phương thức lấy Client theo tên 
 public Client getClient(String ClientName) throws RemoteException; 
 //phương thức lấy mã khách hàng theo mã tài khoản 
 public int getCustomerId(int accountId) throws RemoteException; 
 //phương thức gửi tiền vào tài khoản 
public void deposit(String idAccount, float Amount) throws 
RemoteException; 
 //phương thức rút tiền 
 public void withdraw(String idAccount, float Amount) throws 
RemoteException; 
} 
Bước 4: Tạo class BankManagerImpl thực hiện interface BankManager 
public class BankManagerImpl extends UnicastRemoteObject implements 
BankManager 
{ 
 private Hashtable accounts; 
 private Hashtable Clients; 
 private Connection conn; 
 private Statement s; 
 private int CustomerID; 
 public BankManagerImpl() throws RemoteException 
 { 
 super(); 
 initialize(); 
 } 
public Account getAccount(String accountNumber) throws RemoteException 
 { 
 AccountImpl account = (AccountImpl)accounts.get(accountNumber); 
 return account; 
 } 
 public Client getClient(String ClientID) throws RemoteException 
 { 
 ClientImpl Client = (ClientImpl)Clients.get(ClientID); 
245 
 return Client; 
 //Phương thức rút tiền 
 public void deposit(String idAccount, float amount)throws RemoteException 
 { 
 Account theAccount = (Account)accounts.get(idAccount); 
 theAccount.deposit(amount); 
 accounts.remove(idAccount); 
 accounts.put(idAccount,theAccount); 
 try 
 { 
 Statement s = conn.createStatement(); 
 String sql = "Update account Set Balance ='" + 
theAccount.getBalance() +"' where idAccount = '" + idAccount +"'"; 
 s.executeUpdate(sql); 
 /// update in the dataabase now 
 } 
 catch(Exception e) 
 { 
 e.printStackTrace();; 
 } 
 } 
 public void withdraw(String idAccount, float amount)throws 
RemoteException 
 { 
 Account theAccount = (Account)accounts.get(idAccount); 
 theAccount.withdraw(amount); 
 accounts.remove(idAccount); 
 accounts.put(idAccount,theAccount); 
 try 
 { 
 Statement s = conn.createStatement(); 
 String sql = "Update account Set Balance ='" + 
theAccount.getBalance() +"' where idAccount = '" + idAccount +"'"; 
 s.executeUpdate(sql); 
 /// update in the dataabase now 
 } 
 catch(Exception e) 
 { 
 e.printStackTrace(); 
 } 
246 
 } 
 public void getClientsFromDatabase() 
 { 
 } public void initialize() throws java.rmi.RemoteException 
 { 
 // Create the hashtables 
 accounts = new Hashtable(20); 
 Clients = new Hashtable(10); 
 CreateConnection(); 
 getCustomersFromDatabase(); 
 getAccountsFromDatabase(); 
 } 
 public boolean initializeConnection(String SERVER, String 
DATABASE, String USER_ID, String PASSWORD) throws ClassNotFoundException, 
SQLException 
 { 
 try 
 { 
 String connString = "jdbc:sqlServer://" + SERVER + 
":1433;integratedSecurity=true;databaseName=" + DATABASE; 
 conn = DriverManager.getConnection(connString); 
 s = conn.createStatement(); 
 return true; 
 } 
 catch (SQLException e) 
 { 
 return false; 
 } 
 catch (Exception e) 
 { 
 e.printStackTrace(); 
 return false; 
 } 
 } 
 public void CreateConnection() 
 { 
 if(conn == null) 
 try 
 { 
 initializeConnection("localhost", "QLNH", "root", ""); 
247 
 } 
 catch(Exception e) 
 { 
 e.printStackTrace(); 
 } 
 } 
 public int getCustomerId(int idAccount) 
 { ArrayList ids = new ArrayList(); 
 try 
 { 
 Statement s = conn.createStatement(); 
 String sql = "Select IdCustomer from accountCustomer where 
idAccount ='" + idAccount + "'"; 
 ResultSet r = s.executeQuery(sql); 
 while(r.next()) 
 { 
 ids.add(r.getInt("IdCustomer")); 
 } 
 } 
 catch (Exception ex) 
 { 
 ex.printStackTrace(); 
 } 
 return ids.get(0).intValue(); 
 } 
 public void getCustomersFromDatabase() 
 { 
 try 
 { 
 Statement s = conn.createStatement(); 
 String sql = "Select * from customer"; 
 ResultSet r = s.executeQuery(sql); 
 while(r.next()) 
 { 
 int idCustomer = r.getInt("IdCustomer"); 
 String name = r.getString("Name"); 
 String surname = r.getString("Surname"); 
 Client newClient = new ClientImpl(this, name + " " + surname); 
 Clients.put(String.valueOf(idCustomer), newClient); 
 } 
248 
 } 
 catch (Exception ex) 
 { 
 ex.printStackTrace(); 
 } 
 } 
 public void getAccountsFromDatabase() 
 { 
 System.out.println("------------------------------------"); 
 System.out.println("Reading accounts from the database:"); 
 try 
 { 
 int counter = 0; 
 Statement s = conn.createStatement(); 
 Statement s1 = conn.createStatement(); 
 String sql = "Select * from accountcustomer"; 
 ResultSet r = s.executeQuery(sql); 
 while(r.next()) 
 { 
 int idCustomer = r.getInt("IdCustomer"); 
 int idAccount = r.getInt("idAccount"); 
 Client theClient =(ClientImpl)Clients.get(String.valueOf(idCustomer)); 
 Account newAccount = new 
 AccountImpl(this,theClient,String.valueOf(idAccount),0); 
 accounts.put(String.valueOf(idAccount), newAccount); 
 System.out.println("Customer:"+ newAccount.getClient().getName() + " 
- Account:" + String.valueOf(idAccount)); 
 counter++; 
 } 
 for(int i=1;i<=counter;i++) 
 { 
 if(accounts.containsKey(String.valueOf(i))) 
 { 
 sql = "Select Balance from account where idAccount = '" + i + "'"; 
 ResultSet r1 = s1.executeQuery(sql); 
 r1.next(); 
 float balance = r1.getFloat("Balance"); 
 Account theAccount = (Account)accounts.get(String.valueOf(i)); 
 theAccount.setBalance(balance); 
 accounts.remove(String.valueOf(i)); 
249 
 accounts.put(String.valueOf(i),theAccount); 
 } 
 } 
 s.close(); 
 } 
 catch (Exception ex) 
 { 
 ex.printStackTrace(); 
 } 
Bước 5:Tạo Form BankSystem Server có giao diện như sau 
Thực hiện code cho button Connect và Disconnect 
Phương thức ConnectServer 
private void ConnectServer( 
{..... 
m_bankManager = new BankManagerImpl(); 
 if(m_Registry == null) 
 m_Registry = LocateRegistry.createRegistry(1234); 
 m_Registry.rebind("BankSystem", m_bankManager); 
 m_connected = true; 
..... 
} 
 Phương thức DisconnectServer() 
private void DisconnectServer() 
 { 
 m_bankManager = null; 
 m_Registry.unbind("BankSystem"); 
 m_connected = false; 
 } 
 Về phía người dùng tạo interface Client 
250 
public interface Client extends Remote 
 { 
 //Phương thức trả về ngân hàng quản lý Client này 
 public BankManager getBankManager() throws RemoteException; 
 //Phương thức trả về tên của Client 
 public String getName() throws RemoteException; 
 } 
Tạo ClientImpl thực hiện interface Client 
public class ClientImpl implements Client, Serializable 
 { 
 private BankManager bankManager; 
 private String ClientName; 
 public ClientImpl(BankManager bm, String name) 
 { 
 this.bankManager = bm; 
 this.ClientName = name; 
 } 
 public BankManager getBankManager() throws RemoteException 
 { 
 return bankManager; 
 } 
 public String getName() throws RemoteException 
 { 
 return ClientName; 
 } 
 } 
 Tạo Jframe BanhkUser có giao diện như yêu cầu đề bài: 
public class BankUser extends javax.swing.JFrame { 
 public BankUser() { 
 initComponents(); 
 } 
 // Code chức năng mở của sổ 
private void formWindowOpened(java.awt.event.WindowEvent evt) { 
 try 
 { 
 m_Registry = LocateRegistry.getRegistry("localhost" ,1234); 
 m_bankManager = (BankManager) m_Registry.lookup("BankSystem"); 
 } 
 catch (NotBoundException notBoundException) 
251 
 { 
 System.out.println("Not Bound: " + notBoundException); 
 } 
 catch (RemoteException remoteException) 
 { 
 System.out.println("Remote Exception: " + remoteException); 
 } 
 Code cho button QueryDatabase 
private void btnQrDatabaseActionPerformed(java.awt.event.ActionEvent evt) 
{ 
 try 
 { 
 if(txtCustomerID.getText().length() > 0) 
 { 
 System.out.println("opps: " + txtCustomerID.getText() + "000"); 
 Client Client = m_bankManager.getClient(txtCustomerID.getText()); 
 txtCustomerID.setText(""); 
 System.out.println("Currently in the database there \n is this 
customer with the requested ID: " + Client.getName()); 
 txa_printArea.setText("Currently in the database there \n is this 
customer with the requested ID: " + Client.getName()); 
 } 
 else 
 { 
 if(txtAccountID.getText().length() > 0) 
 { 
 Account account = m_bankManager.getAccount(txtAccountID.getText()); 
 txtAccountID.setText(""); 
 System.out.println("Currently in the database there is \n this 
account with the requested ID: " + account.getClient().getName()); 
 txa_printArea.setText("Currently in the database there is \n this 
account with the requested ID: " + account.getClient().getName() + "\n 
Balance: " + account.getBalance()); 
 } 
 } 
 } 
 catch (RemoteException remoteException) 
 { 
 } 
 } 
252 
Code cho button Deposit 
private void btnDepositActionPerformed(java.awt.event.ActionEvent evt) { 
 try 
 { 
 if(txtAccIDtoDeposit.getText().length() > 0 && 
txtAmountToDeposit.getText().length() > 0) 
 { 
 m_bankManager.deposit(txtAccIDtoDeposit.getText(), 
Float.parseFloat(txtAmountToDeposit.getText())); 
 Account account = 
m_bankManager.getAccount(txtAccIDtoDeposit.getText()); 
 txa_printArea.setText("The account was credited \n as follows:" + 
account.getClient().getName() + "\nBalance: " + account.getBalance()); 
 } 
 } 
 catch (RemoteException remoteException) 
 { 
 System.err.println(remoteException); 
 } 
 } 
 Code cho button WithDraw 
private void btnWithDrawActionPerformed(java.awt.event.ActionEvent evt) { 
try 
 { 
 if(txtAccIDtoWithDraw.getText().length() > 0 && 
txtAmountToWithDraw.getText().length() > 0) 
 { 
 m_bankManager.withdraw(txtAccIDtoWithDraw.getText(), 
Float.parseFloat(txtAmountToWithDraw.getText())); 
Account account = m_bankManager.getAccount(txtAccIDtoWithDraw.getText()); 
txa_printArea.setText("The account was credited \n as follows:" + 
account.getClient().getName() + "\nBalance: " + account.getBalance()); 
 } 
 } 
 catch (RemoteException remoteException) 
 { 
 System.err.println(remoteException); 
 } 
 } 
253 
TÀI LIỆU THAM KHẢO 
[1]. Cay S. Horstmann. Core Java Volum I - Fundamentals, Tenth Edition. NewYork : 
Prentice Hall. 2016. 
[2]. Cay S. Horstmann. Core Java Volum II - Advanced Features, Tenth Edition. New 
York : Prentice Hall. 2017 
[3].Eng.haneen Ei-masry, Java database connection, Islamic University of Gaza 
Faculty of Engineering Department of Computer Engineering ECOM 4113: DataBase 
Lab, 2014. 
[4]. Angelos Stavrou, Advanced Network Programming Lab using Java, Network 
Security, ISA 656, Angelos Stavrou. 
[5]. Marenglen Biba, Ph.D, manual for Lab practices, Remote Method Invocation 
Three Tier Application with a Database Server, Department of Comsputer Science, 
University of New York. 
[6].Elliotte Rusty Harold. Java Network Programming, Fourth Edition. O'Reilly Media, 
2013. 
[7]. Đoàn Văn Ban. Lập trình hướng đối tượng với JAVA. Nhà xuất bản Khoa học và 
Kỹ thuật, 2005. 
[8]. ThS. Dương Thành Phết. Bài tập thực hành Chuyên đề 1 CNPM- Java. Khoa CNTT- 
Trường ĐH Công nghệ TP.HCM. 
[9].https://www.oracle.com/technetwork/java/socket-140484.html# 
[10]. https://personales.unican.es/corcuerp/java/Labs/LAB_22.htm 
[11].  
[12].  
[13]. https://www.academia.edu/35283541/Bài tập môn lập trình hướng đối tượng 
254 

File đính kèm:

  • pdftai_lieu_hoc_tap_lap_trinh_mang.pdf