Thứ Hai, 15 tháng 7, 2013

Java: Xây dựng chương trình Client - Server ở chế độ có nối kết (TCP)

         
 Dịch vụ Echo được thiết kế theo kiến trúc Client-Server sử dụng Socket làm phương tiện giao tiếp. Cổng mặc định dành cho Echo Server là 7, bao gồm cả hai chế độ có nối kết và không nối kết.
Chương trình TCPEchoClient sẽ nối kết đến EchoServer ở chế độ có nối kết, lần lượt gửi đến Echo Server 10 ký tự từ ‘0’ đến '9', chờ nhận kết quả trả về và hiển thị chúng ra màn hình.

1. Lớp TCPEchoClient.java
import java.io.*;
import java.net.Socket;
public class TCPEchoClient{
        public static void main(String args[]){
               try{
                       Socket s = new Socket(args[0],7);
                       InputStream is = s.getInputStream();
                       OutputStream os = s.getOutputStream();
                       for(int i='0';i<='9';i++){
                              os.write(i);
                              int ch = is.read();
                              System.out.print((char)ch);
                       }                      
               }
               catch(IOException ie){
                       System.out.print("Error: " +ie);
               }
        }
} 
        Chương trình STCPEchoServer cài  đặt một Echo Server phục vụ tuần tự  ở chế  độ có nối kết. Server lắng nghe trên cổng mặc định số 7.

2. Lớp STCPEchoServer.java  (Server phục vụ tuần tự)
import java.net.*;
import java.io.*;
public class STCPEchoServer{
        public final static int defaultPort = 7;
        public static void main(String[] args){
        try{
               ServerSocket ss = new ServerSocket(defaultPort);
                while (true) {
                    try { 
                        Socket s = ss.accept(); 
                        OutputStream os = s.getOutputStream();
                        InputStream is = s.getInputStream();
                        int ch=0;
                        while(true) { 
                            ch = is.read();
                            if(ch == -1) break;
                            os.write(ch);
                      } 
                        s.close(); 
                    } 
                    catch (IOException ie) {
                        System.err.println("Connection Error: "+ie);
                    } 
                } 
         }
         catch (IOException ie) {
               System.err.println("Server Creation Error:"+ie);
         }
        }
}   
        Hai chương trình này có thể nằm trên hai máy khác nhau. Trong trường hợp đó khi thực hiện chương trình TCPEchoClient phải chú ý nhập đúng địa chỉ IP của máy tính đang chạy chương trình STCPEchoServer. Xem địa chỉ IP của một máy tính Windows bằng lệnh ipconfig.
3. Lớp PTCPEchoServer.java (Server phục vụ song song)
import java.net.*;
import java.io.*;
public class PTCPEchoServer {
    public final static int defaultPort = 7; // Cong mac dinh
    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(defaultPort); //Tao socket cho server
            while (true) {
                try {
                    Socket s = ss.accept(); // Lang nghe cac yeu cau ket noi
                    RequestProcessing rp = new RequestProcessing(s); // Tao phan xu ly 
                    rp.start(); // Khoi dong phan xu ly cho Client hien tai
                } 
                catch (IOException e) {
                    System.out.println("Connection Error: "+e);
                } 
            }
        }
        catch (IOException e) {
            System.err.println("Create Socket Error: "+e);
        } 
    } 
}
class RequestProcessing extends Thread {
    Socket channel; //Socket cua kenh ao noi voi Client hien tai
    public RequestProcessing(Socket s){
        channel = s; // Nhan Socket cua kenh ao noi voi Client
    }
    public void run() {
        try {
            OutputStream os = channel.getOutputStream();
            InputStream is = channel.getInputStream();
            while (true) {
                int n = is.read();        // Nhan ky tu tu Client
                if (n == -1) break;    // Thoat neu kenh ao bi xoa
                os.write(n);              //  Gui ky tu nhan duoc ve Client
            }
        }
        catch (IOException e) {
            System.err.println("Request Processing Error: "+e);
        }
    }
}
Biên dịch và thực thi chương trình. Sau đó mở thêm 2 của sổ DOS khác để thực thi chương trình TCPEchoClient nối kết tới PTCPEchoServer. Ta sẽ nhận thấy rằng PTCPEchoServer có khả năng phục vụ đồng thời nhiều Client. 

Thứ Ba, 9 tháng 7, 2013

Java: Xây dựng lớp Hình tròn với 2 thuộc tính: lớp Diem để xác định Tâm của hình tròn, Bán kính của hình tròn

1. Hãy xây dựng lớp Diem cùng với chứa các đối tượng điểm trong mặt phẳng và xây dựng phương thức sau:
        - Toán tử tạo lập
        - Phương thức in một đối tượng thuọc lớp Diem
        - Tính khoảng cách giữa hai điểm
2. Xây dựng lớp HinhTron chứa các đốI tượng là các hình tròn với 2 thuộc tính là 1 đối tượng thuộc lớp Diem để xác định tâm của hình tròn một giá trị nguyên để xác định bán kinh của hình tròn. Cài đặt các phương thức:
        - Xây dựng các toán tử tạo lập: HinhTron(),
        - HinhTron(Diem d, int bk)
        - HinhTron(int bk , Diem d)
        - Tính chu vi, diện tich hình tròn

import java.io.*;
class Diem{
        protected double hd,td;
        Diem (){}
        Diem (int a,int b){
               hd=a;
               td=b;
        }
        void in (){
               System.out.println("("+hd+","+td+")");
        }
        double tinhkc(Diem d1,Diem d2){
               double kc=0;
               kc=Math.sqrt(Math.pow(d1.hd-d2.hd,2)+Math.pow(d1.td-d2.td,2));
               return kc;
        }                          
}
public class HinhTron{
        private Diem O = new Diem();
        private int R;
        HinhTron(){}
        HinhTron(Diem d,int bk){
               O=d;
               R=bk;
        }
        HinhTron(int bk,Diem d){
               O=d;
               R=bk;
        }
        double chuvi(){
                double cv=0;
               cv=2*Math.PI*R;
               return cv;     
        }
        double dtich(){
                double dt;
                dt=R*R*Math.PI;
                return dt;
        }
        static String nhapgt() throws IOException{
                String str;
               InputStreamReader isr = new InputStreamReader(System.in);
               BufferedReader br = new BufferedReader(isr);
               str= br.readLine();
               return str;
        }
        static Diem nhapdiem() throws IOException{
               int a,b;
               System.out.println("Toa do tam: ");
               System.out.print("Hoanh do: ");
               a=Integer.valueOf(nhapgt()).intValue();
               System.out.print("Tung do: ");
               b=Integer.valueOf(nhapgt()).intValue();
               Diem nd=new Diem(a,b);
               return nd;
        }
        static HinhTron nhapht() throws IOException{
               int bk;
               Diem tam=new Diem();
               tam=nhapdiem();
               System.out.print("Nhap do dai ban kinh: ");
               bk=Integer.valueOf(nhapgt()).intValue();
               HinhTron ht=new HinhTron(tam,bk);
               return ht;
        }
        public static void main(String args[]) throws IOException{     
               HinhTron HT=new HinhTron();
               HT=nhapht();
               System.out.println("Chu vi: "+HT.chuvi());
               System.out.println("Dien tich : "+HT.dtich());
        }     
}

Thứ Bảy, 6 tháng 7, 2013

Java: Xây dựng lớp Phân Số và các Hàm toán học (cộng, trừ, nhân, chia, nghịch đảo) của Phân số


Thiết kế lớp PhanSo (Phân số) gồm có:
        + 2 thuộc tính tử số và mẫu số thuộc kiểu nguyên
        + Các phương thức:
               - Phương thức khởi tạo.
               - Phương thức in phân số.
               - Phương thức nghịch đảo phân số.
               - Phương thức trả về giá trị thực của phân số
               - Hàm cộng, trừ, nhân, chia 2 phân số.
        + Phương thức main() sử dụng lớp PhanSo.
-------------------------------------------- 
import java.io.*;
public class PhanSo{
        protected int ts,ms;
        PhanSo(){
        }
        PhanSo(int t, int m){
               ts=t;
               ms=m;
        }
        static int nhapgt() throws IOException{            
               InputStreamReader isr = new InputStreamReader(System.in);
               BufferedReader br = new BufferedReader(isr);
               String str = br.readLine();
               return Integer.valueOf(str).intValue();
        }     
        PhanSo nhapps(int x) throws IOException{
               int tu,mau;
               System.out.println("Nhap phan so thu: " +x);
               System.out.print("Tu so: ");
               tu=nhapgt();
               System.out.print("Mau so: ");
               do{
                       mau=nhapgt();
                       if(mau==0) System.out.print("Nhap lai mau so");
               }while(mau==0);
               PhanSo ps = new PhanSo(tu,mau);
               return ps;
        }
        static int UCLN(int a, int b){
               while(a!=b){
                       if(a>b) a=a-b;
                       else b=b-a;
               }
               return a;
        }
        static PhanSo toigian(PhanSo ps){
               PhanSo phanso = new PhanSo();
               phanso.ts = ps.ts/UCLN(Math.abs(ps.ts),Math.abs(ps.ms));
               phanso.ms = ps.ms/UCLN(Math.abs(ps.ts),Math.abs(ps.ms));
               return phanso;
        }
        static PhanSo tong(PhanSo ps1, PhanSo ps2){
               PhanSo phanso = new PhanSo();
               phanso.ts= ps1.ts*ps2.ms + ps2.ts*ps1.ms;
               phanso.ms= ps1.ms*ps2.ms;
               if(phanso.ts!=0)
                       phanso=toigian(phanso);
               return phanso;
        }
        static PhanSo hieu(PhanSo ps1, PhanSo ps2){
               PhanSo phanso = new PhanSo();
               phanso.ts = ps1.ts*ps2.ms - ps2.ts*ps1.ms;
               phanso.ms = ps1.ms*ps2.ms;
               if(phanso.ts!=0)
                       phanso = toigian(phanso);
               return phanso;
        }
        static PhanSo tich(PhanSo ps1, PhanSo ps2){
               PhanSo phanso = new PhanSo();
               phanso.ts = ps1.ts*ps2.ts;
               phanso.ms = ps1.ms*ps2.ms;
               if(phanso.ts!=0)
                       phanso = toigian(phanso);
               return phanso;
        }
        static PhanSo thuong(PhanSo ps1,PhanSo ps2){
               PhanSo phanso=new PhanSo();
               phanso.ts = ps1.ts*ps2.ms;
               phanso.ms = ps1.ms*ps2.ts;
               if(phanso.ts!=0)
                       phanso=toigian(phanso);
               return phanso;
        }
        static void Hienthi(PhanSo ps){
               if(ps.ts==0 || ps.ms==1) System.out.print(ps.ts);
               else System.out.println(ps.ts+"/"+ps.ms);
        }
        public static void main(String args[]) throws IOException{
               PhanSo ps1 = new PhanSo();
               PhanSo ps2 = new PhanSo();
               ps1=ps1.nhapps(1);
               ps2=ps2.nhapps(2);
               if(ps1.ts!=0)
                       ps1=toigian(ps1);
               if(ps2.ts!=0)
                       ps2=toigian(ps2);
               System.out.println("Phan so 1 o dang toi gian: "); Hienthi(ps1);
               System.out.println();
               System.out.println("Phan so 2 o dang toi gian: "); Hienthi(ps2);
               System.out.println();
               System.out.print("Phan so tong: "); Hienthi(tong(ps1,ps2));
               System.out.print("Phan so hieu: "); Hienthi(hieu(ps1,ps2));
               System.out.print("Phan so tich: "); Hienthi(tich(ps1,ps2));
               if (ps2.ts!=0){
                       System.out.print("Phan so thuong(phan so 1/phan so 2): ");
                       Hienthi(thuong(ps1,ps2));
               }
               else System.out.print("Khong the thuc hien phep chia phan so 1/phan so 2 ");
                       System.out.println();
               if (ps1.ts!=0){
                       System.out.print("Phan so thuong(phan so 2/phan so 1): ");
                       Hienthi(thuong(ps2,ps1));
                }
               else System.out.print("Khong the thuc hien phep chia phan so 2/phan so 1 ");
                       System.out.println();
            }