Showing posts with label Lập trình mạng. Show all posts
Showing posts with label Lập trình mạng. Show all posts

[ Java ] Code Java tải website về máy tính [ Download URL ]

Chương trình Java download URL:
- Nhập địa chỉ URL cần download
- Kết quả download được lưu tại output.htm, trong thư mục chứa Project

* Để download từ địa chỉ URL cần sử dụng 2 thư viện:
    + java.net.URL
    + java.net.URLConnection

[Code Java]

/******************************************************************************
 http://lap-trinh-may-tinh.blogspot.com/
******************************************************************************/

package download_java;
import java.util.Scanner;

public class  Download_java
{
  public static void main(String[] args) throws Exception
  {
    // Nhập địa chỉ URL cần download
      Scanner in=new Scanner(System.in);
    System.out.print("\n Nhập URL: ");
    String str_url=in.nextLine();
    // Địa chỉ URL cần download
    java.net.URL url = new java.net.URL(str_url);
    java.net.URLConnection con = url.openConnection();

    java.io.InputStream is=con.getInputStream();

    // Kết quả được lưu trên output.htm trong thư mục chứa Project
    String output_file="output.htm";
    java.io.FileOutputStream os=new java.io.FileOutputStream(output_file);

    int BUF_SIZE=1024; // KB
    byte[] buffer = new byte[BUF_SIZE];
   
    while (true)
    {
      int n = is.read(buffer);  // đọc data URL
      if (n>0) os.write(buffer,0,n);     // ghi vào file
      if (n<0) break;    // kế thúc đọc
    }
  }
}

[Download Project tại đây]

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Tài liệu: Lập trình hướng đối tượng JAVA core dành cho người mới bắt đầu học lập trình [Click để xem]

# Khoá học online: Lập trình Java trong 4 tuần [Click để xem]

[ Lập trình mạng với Java ] Sử dụng PIPE mô phỏng Client - Server, tính tổng dãy số nhập từ bàn phím

/*
Sử dụng kỹ thuật Pipe mô phỏng Client - Server 

Yêu cầu:
- Client gửi cho Server dãy số nhập vào từ bàn phím, chờ kết quả nhận được từ Server hiện thị ra màn hình
- Server nhận dãy số từ Client, tính tổng các số, tổng lần lượt được gửi cho Client.

*/

// Class Server (PipedEchoServer)----------------------------------------------------------

package pipedecho;

import java.io.*;

public class PipedEchoServer extends Thread
{
    PipedInputStream readPipe;
    PipedOutputStream writePipe;
    int ch;
    int tong=0;

    // khoi tao
public PipedEchoServer(PipedInputStream readPipe, PipedOutputStream writePipe)
{
    this.readPipe = readPipe;
    this.writePipe = writePipe;
    System.out.println("Server is starting . . .");
}

// nhan du lieu tu client
public void Nhan_DuLieu_Tu_Client(){
        try {
            ch = readPipe.read();
            tong =tong+Integer.valueOf(String.valueOf((char)ch));          
        } catch (IOException ex) {
           System.out.print(" Co loi xay ra khi nhan du lieu tu client: "+ex.toString());
        }
}

//gui ket qua da xu ly cho client

public void GuiTong(){
    try{            
   writePipe.write(tong);      
  }catch (IOException ex) {
              System.out.print(" Co loi xay ra khi gui cho Client: "+ex.toString());
  }
}

public void run()
{
    while(true) {
        Nhan_DuLieu_Tu_Client();     
        GuiTong();      
       
    }
}
}


// Class Client (PipedEchoClient)----------------------------------------

package pipedecho;
import java.io.*; 

public class PipedEchoClient extends Thread { 
    PipedInputStream readPipe; 
    PipedOutputStream writePipe; 
    int ch;
    
    public PipedEchoClient(PipedInputStream readPipe, PipedOutputStream writePipe){ 
        this.readPipe = readPipe; 
        this.writePipe = writePipe; 
        System.out.println("Client creation");         
    } 
  
    // doc 1 ky tu tu ban phim, gui ky tu do cho server
    public void Gui_Server(){   
        try {           
           ch=System.in.read(); 
           writePipe.write(ch);
        } catch (IOException ex) {
            System.out.print(" Co loi xay ra khi gui cho Server: "+ex.toString());
        }
        
    }
    
    // nhan 1 ky tu tu server
    public void Nhan_KQ_Tu_Server() {
        
        try {            
            ch = readPipe.read();
        } catch (IOException ex) {
           System.out.print(" Co loi xay ra khi nhan ket qua tu Server: "+ex.toString());
        }
        
    }
    
    // In ket qua nhan duoc
    public void InKetQua(){
        int Kq=Integer.valueOf(String.valueOf(ch));
        System.out.print("\n Tong: "+Kq); 
    }
    
    // thuc thi
    public void run()
    { 
        while(true) {                         
                Gui_Server();               
                Nhan_KQ_Tu_Server();
                InKetQua();               
        }
    }
}


// Class main (PipedEcho)-------------------------------------------------


package pipedecho;

import java.io.*; 

public class PipedEcho { 
    public static void main(String argv[]){ 
        try{   
            PipedOutputStream cwPipe = new PipedOutputStream(); 
            PipedInputStream crPipe = new PipedInputStream(); 
            
            PipedOutputStream swPipe = new PipedOutputStream(crPipe); 
            PipedInputStream srPipe = new PipedInputStream(cwPipe); 
            
            PipedEchoServer server = new PipedEchoServer(srPipe,swPipe); 
            PipedEchoClient client = new PipedEchoClient(crPipe,cwPipe); 
       
            server.start();
            client.start();
            
        } catch(IOException ie) { 
            System.out.println("Pipe Echo Error:"+ie); 
        }
    }

}


/*
Lưu ý: Viết 3 class trên cùng một project, có tên package: pipedecho. Khi chạy thực thi lớp PipedEcho
*/

 [Tải Code Chương trình tại đây (Lưu ý: Sau 5s, click Bỏ qua quảng cáo - Skin Ad)]

[ Lập trình mạng với Java ] Lập trình SOCKET kết nôi Client - Server để tính tổng 2 số

Lập trình SOCKET kết nôi Client - Server để tính tổng 2 số

/* 
 Viết chương trình:
  - Client: Nhập vào từ bàn phím 2 số nguyên (a,b). Client chờ nhận kết quả từ Server để in ra màn hình
 - Server: Nhận 2 số nguyên mà Client vừa gửi, tính tổng của chúng và gửi kết quả cho Client
*/ 

//----------CLIENT----------------------------------------
import java.net.UnknownHostException; 
import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.IOException; 
import java.net.Socket; 


public class Socket_tong2so_client {

    public static void main(String []args) throws IOException 
    { 
        System.out.println("Client dang ket noi voi Server... "); 
        String a,b,tong; 

        //tao socket de ket noi toi server, Locallhost: server mặc định 
        Socket ClientSocket = new Socket("Localhost", 1234); 

        //thong bao da ket noi thanh cong 
        System.out.println("Da ket noi voi Server! "); 

        //tao luong nhap du lieu tu ban phim 
        DataInputStream inFromUser = new DataInputStream(System.in); 

        //tao luong nhan du lieu tu server 
        DataInputStream inFromServer = new DataInputStream(ClientSocket.getInputStream()); 

        //tao luong gui du lieu len server 
        DataOutputStream outToServer = new DataOutputStream(ClientSocket.getOutputStream()); 

        // nhap du lieu tu ban phim
        try{ 
            System.out.println("\n Nhap a :"); 
            a=inFromUser.readLine(); 
            System.out.println("\n Nhap b :"); 
             b=inFromUser.readLine(); 

            // gui len server 
             outToServer.writeBytes(a+'\n'); 
            outToServer.writeBytes(b+'\n'); 
        }catch(UnknownHostException e) 
        { 
            System.err.println("Server Not Found"); 
            System.exit(1); 
        }catch(IOException e) 
        { 
            System.err.println("Cannot make a connection"); 
            System.exit(1); 
        } 
         
        //nhan ve tu server 
        tong=inFromServer.readLine(); 

        //in ra man hinh 
        System.out.println("\n Ket qua :"+tong); 

        //dong luong gui du lieu len server 
        outToServer.close(); 

        //dong luong nhan du lieu tu server 
        inFromServer.close(); 

        //dong socket client 
        ClientSocket.close(); 
    } 



//----------SERVER----------------------------------------


import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.IOException; 
import java.net.ServerSocket; 
import java.net.Socket; 

public class Socket_tong2so_server {
    public static void main(String []args) throws IOException 
    { 
        System.out.println("Server dang khoi dong... "); 
        String so1,so2,so3; 
        int tong; 

        // tao server socket 
        ServerSocket server = new ServerSocket(1234); 
        System.out.println("Server da san sang! "); 

        //tao 1 socket do ket noi tu client toi server 
        Socket connectionSocket = server.accept(); 

        //tao luong nhan du lieu tu client 
        DataInputStream inFromClient = new DataInputStream(connectionSocket.getInputStream()); 

        // tao luong gui du lieu toi client 
        DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); 

        // truyen du lieu tu client vao 2 bien so1 va so2 
        so1 = inFromClient.readLine(); 
        so2 = inFromClient.readLine(); 

        //ep so1 va so2 tu kieu String sang kieu Integer 
        int a = Integer.parseInt(so1); 
        int b = Integer.parseInt(so2); 

        //tinh tong a + b 
        tong = a + b; 

        //ep tong  sang kieu String 
        so3 = String.valueOf(tong); 

        //gui so3 ve client 
        outToClient.writeBytes(so3+'\n'); 

        //dong luong nhan du lieu tu client 
        inFromClient.close(); 

        //dong luong gui du lieu ve client 
        outToClient.close(); 

        //dong server socket 
        server.close(); 
    } 



/* 
Chú ý: Run class Server trước sau đó Run class Client
*/
 

Chúc các bạn thành công!

 




[Tham khao: Internet]

[ Java ] Sử dụng InputStream / OutputStream

Sử dụng luồng vào ra InputStream và OutputStream trong Java

/* ----------------------------------------------------------------------------------------
Ví dụ 1: InputStream - System.in;
- Nhập vào từng ký tự từ bàn phím, In ký tự vừa nhập, kết thúc khi nhập phím 'q'

*/
package inputstream1;
import java.io.*;
public class InputStream1 {
public static void main(String args[])
{
InputStream is = System.in;
while (true)
{
try
{
int ch = is.read(); // doc 1 ky tu tu ban phim
if (ch ==-1 || ch =='q')
break;
System.out.print((char)ch);

} catch (IOException ie)
{
System.out.print("Error: "+ie);
}
}


}
}

/*----------------------------------------------------------------------------------------------
Ví dụ 2: InputStream - System.in
Nhập vào từ bàn phú dãy ký tự lưu vào mảng b, in mảng b ra màn hình

*/


package inputstream2;
import java.io.*;
public class InputStream2
{
public static void main(String args[])
{
InputStream is = System.in; // KeyBoard = System.in

while (true)
{
try
{
int num = 10;//is.available();
if (num > 0)
{
byte[] b = new byte[num];
int result = is.read(b);
if (result == -1) break;
String s = new String(b);
System.out.print(s);
} else
{
System.out.print('.');
}
} catch (IOException ie)
{
System.out.print("Error: "+ie);
}
}
}
}

/* -----------------------------------------------------------------------------------------
Ví dụ 3: OutputStream - System.out
In ra màn hình xâu: "Day la vi du OutputStream voi System.out (man hinh) "

*/

ackage outputstream1;

import java.io.*;
public class OutputStream1
{
public static void main(String args[])
{
OutputStream os = System.out;

// Monitor = System.out
try
{
String str = "Day la vi du OutputStream voi System.out (man hinh) \n";
byte b[] = str.getBytes(); // Đổi chuỗi thành mảng các bytes
os.write(b);
} catch (IOException ie)
{
System.out.print("Error: "+ie);
}
}
}


/*----------------------------------------------------------------------------------------------
Ví dụ 4: - InputStream - InputStreammReader - BufferedReader - readLine()
- Nhập vào 2 số nguyên a, b
- Tính tổng 2 số, in kết quả ra màn hình
*/

package inputstreamreadline;
import java.io.*;
public class InputStreamReadLine{
public static void main(String args[])
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

try{
System.out.print("\n Nhap a:");
String xau1=br.readLine();
int a=Integer.valueOf(xau1);// ép kiểu string -> int

System.out.print("\n Nhap b:");
String xau2=br.readLine();
int b=Integer.valueOf(xau2);

int s=a+b;
String str=String.valueOf(s);// ép kiểu int -> string

// in ra nam hinh
OutputStream os = System.out;
PrintWriter xuat = new PrintWriter(os);

xuat.write("Ket qua= ");
xuat.print(str);
xuat.flush();

// System.out.print("\n Tong= "+str);

}catch(IOException e){
System.out.print("Loi "+e.toString());
}

}
}

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Tài liệu: Lập trình hướng đối tượng JAVA core dành cho người mới bắt đầu học lập trình [Click để xem]

# Khoá học online: Lập trình Java trong 4 tuần [Click để xem]

[ Java ] Sử dụng InputStream / OutputStream



Sử dụng luồng vào ra InputStream và OutputStream trong Java

/* ----------------------------------------------------------------------------------------
Ví dụ 1: InputStream - System.in;
- Nhập vào từng ký tự từ bàn phím,  In ký tự vừa nhập, kết thúc khi nhập phím 'q'
*/
package inputstream1;
import java.io.*; 
public class InputStream1 { 
    public static void main(String args[]) 
    {
        InputStream is = System.in;       
        while (true) 
        { 
            try 
            {
                int ch = is.read(); // doc 1 ky tu tu ban phim
                if (ch ==-1 || ch =='q')
                    break; 
                System.out.print((char)ch);
              
            } catch (IOException ie) 
            {
                System.out.print("Error: "+ie); 
            }
        }
        
        
    }
}

/*----------------------------------------------------------------------------------------------
Ví dụ 2: InputStream - System.in
    Nhập vào từ bàn phú dãy ký tự lưu vào mảng b, in mảng b ra màn hình

*/


package inputstream2;
import java.io.*; 
public class InputStream2 
{
    public static void main(String args[])
    {
        InputStream is = System.in; // KeyBoard = System.in 
       
        while (true)
        {
            try
            {
                int num = 10;//is.available(); 
                if (num > 0)
                {
                    byte[] b = new byte[num]; 
                    int result = is.read(b); 
                    if (result == -1) break; 
                    String s = new String(b); 
                    System.out.print(s); 
                } else
                {
                    System.out.print('.');
                }
            } catch (IOException ie)
            {
                System.out.print("Error: "+ie); 
            }
        } 
}
}

/* -----------------------------------------------------------------------------------------
Ví dụ 3:  OutputStream - System.out
   In ra màn hình xâu: "Day la vi du OutputStream voi System.out (man hinh) " 

*/

ackage outputstream1;

import java.io.*; 
public class OutputStream1 
{
    public static void main(String args[]) 
    {
        OutputStream os = System.out;
    
// Monitor = System.out 
        try
        {
            String str = "Day la vi du OutputStream voi System.out (man hinh) \n";
            byte b[] = str.getBytes(); // Đổi chuỗi thành mảng các bytes 
            os.write(b);
        } catch (IOException ie)
        { 
            System.out.print("Error: "+ie); 
        }
    }
}


/*----------------------------------------------------------------------------------------------
Ví dụ 4: - InputStream - InputStreammReader - BufferedReader - readLine()
- Nhập vào 2 số nguyên a, b
- Tính tổng 2 số, in kết quả ra màn hình
*/

package inputstreamreadline;
import java.io.*;
public class InputStreamReadLine{ 
    public static void main(String args[]) 
    { 
        InputStreamReader isr = new InputStreamReader(System.in); 
        BufferedReader br = new BufferedReader(isr);
        
        try{
            System.out.print("\n Nhap a:");
            String xau1=br.readLine();
            int a=Integer.valueOf(xau1);// ép kiểu string -> int
            
            System.out.print("\n Nhap b:");
            String xau2=br.readLine();
            int b=Integer.valueOf(xau2);
            
            int s=a+b;
            String str=String.valueOf(s);// ép kiểu int -> string
            
            // in ra nam hinh
            OutputStream os = System.out;
            PrintWriter xuat = new PrintWriter(os);
            
            xuat.write("Ket qua= ");
            xuat.print(str);
            xuat.flush();
            
           // System.out.print("\n Tong= "+str);
        
        }catch(IOException e){
            System.out.print("Loi "+e.toString());
        }
        
    }
}


>>> GAME CỰC ĐỈNH CHO MOBILE <<<

[ Java ] Lập trình truyền thông - Sử dụng Pipe - Ví dụ1

/*  Pipe - java
Ví dụ1: Viết chương trình mô phỏng Client-Server
- Client gửi cho Server 1 xâu ký tự (nhập từ bàn phím), chờ nhận xâu kết quả từ Server rồi in ra màn hình.
- Server nhận xâu ký tự từ Client, đổi xâu đó ra chữ hoa, gửi kết quả lại cho Client.
*/

// --------------------------------------------------------------------------------------------
// Class Sever

package pipedecho;
import java.io.*; 

public class PipedEchoServer extends Thread 
{
    PipedInputStream readPipe; 
    PipedOutputStream writePipe; 
    int ch;

    // khoi tao
public PipedEchoServer(PipedInputStream readPipe, PipedOutputStream writePipe)

    this.readPipe = readPipe; 
    this.writePipe = writePipe; 
    System.out.println("Server is starting . . .");  


// nhan du lieu tu client
public void Nhan_DuLieu_Tu_Client(){
        try {
            ch = readPipe.read();
        } catch (IOException ex) {
           System.out.print(" Co loi xay ra: "+ex.toString());
        }
}

//gui ket qua da xu ly cho client
public void Gui_QK_Cho_Client(){
        try {
            writePipe.write(ch);
        } catch (IOException ex) {
              System.out.print(" Co loi xay ra: "+ex.toString());
        }
}

// Doi chu thuong thanh chu hoa
public void DoiChu(){
    ch = Character.toUpperCase((char)ch);     
}
public void run()

    while(true) { 
        Nhan_DuLieu_Tu_Client();
        DoiChu();
        Gui_QK_Cho_Client();
    }
}
}




// --------------------------------------------------------------------------------------------
// Class Client

package pipedecho;
import java.io.*; 


public class PipedEchoClient extends Thread { 
    PipedInputStream readPipe; 
    PipedOutputStream writePipe; 
    int ch;
    
    public PipedEchoClient(PipedInputStream readPipe, PipedOutputStream writePipe){ 
        this.readPipe = readPipe; 
        this.writePipe = writePipe; 
        System.out.println("Client creation");         
    } 
  
    // doc 1 ky tu tu ban phim, gui ky tu do cho server
    public void Gui_Server(){   
        try {           
           ch=System.in.read(); 
           writePipe.write(ch);
        } catch (IOException ex) {
            System.out.print(" Co loi xay ra: "+ex.toString());
        }
        
    }
    
    // nhan 1 ky tu tu server
    public void Nhan_KQ_Tu_Server() {
        
        try {            
            ch = readPipe.read();
        } catch (IOException ex) {
           System.out.print(" Co loi xay ra: "+ex.toString());
        }
        
    }
    
    // In ket qua nhan duoc
    public void InKetQua(){
        System.out.print((char)ch); 
    }
    
    // thuc thi
    public void run()
    { 
        while(true) {          
                Gui_Server();
                Nhan_KQ_Tu_Server();
                InKetQua();               
        }
    }
}





// --------------------------------------------------------------------------------------------
// Class Main
package pipedecho;

import java.io.*; 

public class PipedEcho { 
    public static void main(String argv[]){ 
        try{   
            PipedOutputStream cwPipe = new PipedOutputStream(); 
            PipedInputStream crPipe = new PipedInputStream(); 
            
            PipedOutputStream swPipe = new PipedOutputStream(crPipe); 
            PipedInputStream srPipe = new PipedInputStream(cwPipe); 
            
            PipedEchoServer server = new PipedEchoServer(srPipe,swPipe); 
            PipedEchoClient client = new PipedEchoClient(crPipe,cwPipe); 
       
            server.start();
            client.start();
            
        } catch(IOException ie) { 
            System.out.println("Pipe Echo Error:"+ie); 
        }
    }

}

// Chú ý: Tạo 3 class trong cùng 1 project (PipedEcho)

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Tài liệu: Lập trình hướng đối tượng JAVA core dành cho người mới bắt đầu học lập trình [Click để xem]

# Khoá học online: Lập trình Java trong 4 tuần [Click để xem]