Tải bản đầy đủ (.docx) (37 trang)

tài liệu lập trình mạng

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (231.44 KB, 37 trang )

Mục lục

1


Câu 2: Viết chương trình Client – Server thực hiện các chức năng: client gửi yêu cầu
kết nối, client gửi lên xâu ký tự, server gửi về xâu đảo ngược.
*file Cilent
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import javax.swing.JOptionPane;
public class TCPClient {
public static void main(String []args) throws IOException{
//Khai bao socket để làm việc với server qua địa chỉ IP và Cổng
//Chú ý cổng phải trùng với khai báo trên server
Socket cs = new Socket("127.0.0.1", 1234);
//Khai báo 2 đối tượng để đọc và ghi dữ liệu
DataInputStream din = new DataInputStream(cs.getInputStream());
DataOutputStream dout = new DataOutputStream(cs.getOutputStream());
String strSend, strReturn;
try {
while (true) {
//Hộp thoại để nhập dữ liệu đầu ra là kiểu string
strSend = JOptionPane.showInputDialog(null,"Please enter
text to dialog for send to server:");
//gửi dữ liệu vào Stream để gửi lên Server
dout.writeUTF(strSend);
//Đọc dữ liệu từ Stream
strReturn = din.readUTF();


//Hộp thoại hiển thị dữ liệu
2


JOptionPane.showMessageDialog(null, "The text from
Server: "+strReturn);
}
} catch (Exception e) { cs.close();}
}
}
*file Server:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main (String [] args) throws IOException{
//Khai báo socket trên server với cổng 1234
ServerSocket ss = new ServerSocket(1234);
//In thông báo ra màn hình
System.out.println("Server is Open");
//Khai bao socket phía client chú ý "ss" là socket phía server
Socket cs = ss.accept();
//Khai báo 2 đối tượng để đọc ghi dữ liệu từ socket
DataInputStream din = new DataInputStream(cs.getInputStream());
DataOutputStream dout = new DataOutputStream(cs.getOutputStream());
String strReceive, strReturn;
try {
while (true) {

//Đọc dữ liệu trong Stream gửi từ Client
3


strReceive = din.readUTF();
//Sử dụng phương thức Reverse() để đảo ngược xâu ký tự
strReturn = new StringBuffer(strReceive).reverse().toString();
//Server ghi dữ liệu vào stream để gửi cho Client
dout.writeUTF(strReturn);
}
} catch (Exception e) {
//Đóng socket nếu gặp lỗi
cs.close(); ss.close();
}
}
}
Câu 3: Viết chương trình thực hiện nhân hai ma trận 3*3 nhập từ bàn phím, lưu kết
quả vào tệp nhị phân.
Cách 1: sử dụng tập tin nhị phân (với tập tin nhị phân sử dụng InputStream và
OutputStream)
package SoNguyenTo;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class BinaryFile {
private static DataInputStream din;

private static DataOutputStream dout;
private static Scanner sc;
4


public static void main (String [] args) throws FileNotFoundException,
IOException, ClassNotFoundException{
sc = new Scanner(System.in);
int n,i,j;
String kq = "1 ", readData;
boolean kt;
System.out.println("Nhap n: ");
n = Integer.parseInt(sc.nextLine());
//kiem tra cac so nguyen to nho hon n va gan vao chuoi kq
for (i = 2; i < n; i++) {
kt = true;
for (j = 2; j <= i/2; j++) {
if (i%j==0) {
kt = false; break;
}
}
if (kt==true) { kq += i + " "; }
}
//Ghi du lieu vao file nhi phan
dout = new DataOutputStream(new FileOutputStream("Data.dat"));
dout.writeUTF(kq);
System.out.println("Write data success.");
//Doc du lieu tu file nhi phan
din = new DataInputStream(new FileInputStream("Data.dat"));
readData = din.readUTF();

System.out.println("Data is: " + readData);
}
5


}
Cách 2: sử dụng tập tin text (khi sử dụng tập tin text thì dùng FileWriter và FileReader)
package SoNguyenTo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class TextFile {
private static Scanner sc;
public static void main (String[] args) throws FileNotFoundException,
IOException, ClassNotFoundException {
sc = new Scanner(System.in);
int n,i,j;
String kq = "1 ";
boolean kt;
System.out.println("Nhap n: ");
n = Integer.parseInt(sc.nextLine());
//kiem tra cac so nguyen to nho hon n va gan vao chuoi kq
for (i = 2; i < n; i++) {
kt = true;
for (j = 2; j <= i/2; j++) {
if (i%j==0) {

kt = false; break;
}
6


}
if (kt==true) { kq += i + " "; }
}
//Khai bao đối tượng FileWriter để Ghi du lieu vao file text
FileWriter fw = new FileWriter(new File("Data.txt"));
//Ghi dữ liệu của "kq" vào file Data.txt
fw.write(kq);
fw.close();
System.out.println("Write data success.");
//Khai báo 2 đối tượng để đọc dữ lieu từ file text
FileReader fr = new FileReader(new File("Data.txt"));
StringBuffer sb = new StringBuffer();
//Khai báo mảng để chứa dữ liệu
char ca[] = new char[2];
//Đọc dữ liệu khi nào đọc xong thì kết thúc vòng lặp
while(fr.ready()){
int len = fr.read(ca);
sb.append(ca,0,len);
}
fr.close();
System.out.println("Du lieu doc duoc la: " + sb);
}
}
Câu 4: Viết chương trình Client – Server, server đọc danh sách Username/Password
từ một file văn bản user.txt, client gửi yêu cầu kết nối, server kiểm tra

Username/Password nếu đúng thì cho phép kết nối. Nếu sai thì gửi thông báo “Sai
thông tin đăng nhập” về cho client và đóng kết nối (sử dụng multithread)
* phía Client
7


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String [] args){
try {
Socket cs = new Socket("127.0.0.1", 1234);
// PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
//BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
DataInputStream din = new DataInputStream(cs.getInputStream());
DataOutputStream dout = new
DataOutputStream(cs.getOutputStream());
Scanner scanner = new Scanner(System.in);
String strSend = "", strReturn = "";
while (true) {
strSend = scanner.nextLine();
dout.writeUTF(strSend);
dout.flush();
strReturn = din.readUTF();
System.out.println("Server replied " + strReturn);
}

} catch (IOException e) { e.printStackTrace(); }
}
}
*phía Serve
8


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main (String [] args){
ServerSocket server = null;
while (true) {
Socket client = server.accept();
System.out.println("New Client connected " +
client.getInetAddress().getHostAddress());
ClientHandler clientSock = new ClientHandler(client);
new Thread(clientSock).start();
}
}
//tạo thread
public static class ClientHandler implements Runnable{
private final Socket cs;
public ClientHandler (Socket socket) { this.cs = socket; }
public void run(){
DataInputStream din = null;
DataOutputStream dout = null;

String strReceive, strReturn;
while (true) {
strReceive = din.readUTF();
System.out.printf("Sent from the client: %s\n", strReceive);
9


strReturn = new StringBuffer(strReceive).reverse().toString();
dout.writeUTF(strReturn);
}
}
}
}
Câu 5: Viết chương trình tạo ra một đối tượng FileTWrite kế thừa đối đối tượng
Thread (hoặc cài đặt giao diện Runable), cho phép viết một dãy số ngẫu nhiên vào
tập tin. Đối tượng FileTWriter có thuộc tính tên tập tin cần viết. Viết hàm main tạo
ra 3 đối tượng viết 3 tập tin chạy ở 3 tiến trình đồng thời riêng biệt.
*lớp filewwirter để ghi tập tin
package Bai5;
import java.util.Random;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.*;
public class FileWrite extends Thread {
private static final int xsize = 10;
private int x;
private String name;
public FileWrite (String ten) {
this.name= ten;

}
public void nhap() {
try {
FileWriter fra= new FileWriter(name);
BufferedWriter bw = new BufferedWriter(fra);
10


Random rd=new Random();
for(int i=0;i<=xsize;i++)
{
x = rd.nextInt(xsize);
if(i==9)
bw.write(String.valueOf(x));
else
bw.write(String.valueOf(x) + ",");
}
bw.close();
fra.close();
}catch(IOException ex) {
JOptionPane.showMessageDialog(null, ex.toString(),"Thông báo lỗi",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
* hàm main
package Bai5;
public class Main5 {
public static void main(String[] args) {
FileWrite f1 = new FileWrite("tep1.txt");

f1.start();
FileWrite f2 = new FileWrite("tep2.txt");
f2.start();
FileWrite f3 = new FileWrite("tep3.txt");
f3.start();

}

}

11


Câu 6: Viết chương trình tạo ra một đối tượng FileTReader kế thừa đối đối tượng
Thread (hoặc cài đặt Runable), cho phép đọc nội dung một tập tin và hiển thị lên
màn hình. Đối tượng FileReader có thuộc tính tên tập tin cần mở. Viết hàm main
tạo ra 3 đối tượng đọc 3 tập tin chạy ở 3 tiến trình đồng thời riêng biệt.
*class file Reader để đọc tập tin
package Bai6;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import javax.swing.JOptionPane;
public class FileRead extends Thread{
String name;
public FileRead(String ten){ this.name = ten; }
public void load(){
try {
FileReader fvao = new FileReader(name);
BufferedReader br = new BufferedReader(fvao);

int c;
while((c = br.read()) != -1) { System.out.println(this.name + ": " + c); }
br.close();
fvao.close();
}catch(IOException ex) {
JOptionPane.showMessageDialog(null, ex.toString(),"Thông báo lỗi",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
*hàm main
package Bai6;

12


public class Main6 {
public static void main(String[] args) {
FileRead f1 = new FileRead("file1.txt");
f1.start();
FileRead f2 = new FileRead("file2.txt");
f2.start();
FileRead f3 = new FileRead("file3.txt");
f3.start();
}
}

Câu 7: Viết chương trình tạo ra đối tượng đọc tập tin, viết tập tin chạy ở từng tiến
trình riêng (có xử lý đồng bộ hóa dư liệu). Viết hàm main tạo ra đối tượng viết và
đọc dữ liệu với tập tin giống nhau. Kiểm tra việc đồng bộ hóa dữ liệu.

Tạo file wirter (bài 5) và class reader (bài 6) sau đó sử dụng hàm main để chạy
package Bai7;
import Bai5.FileWrite;
import Bai6.FileRead;
public class Main {
public static void main(String[] args) {
FileWrite fra = new FileWrite("test.txt");
fra.start();
FileRead fvao = new FileRead("test.txt");
fvao.start();
}
}

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
13


* and open the template in the editor.
*/
package InOutPut;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

BTVN ngay
̀ 21/05

Câu 8: Nhập vào đối tượng đường dẫn URL. Hiển thị các thông tin của đường dẫn,
giao thức, tên miền, số hiệu cổng…nếu có và dữ liệu đường dẫn nhận được từ server
lên màn hình
public class Address {

public static void main(String[] args) throws MalformedURLException, IOException {
URL u = new URL(" ");
System.out.println("The protocol is" + u.getProtocol());
System.out.println("The host is " + u.getHost());
System.out.println("The port is " + u.getPort());
System.out.println("The file is " + u.getFile());
URLConnection uc = u.openConnection();
String thisLine;
DataInputStream dis = new DataInputStream(u.openStream());
while ((thisLine = dis.readLine()) != null) {
14


System.out.println(thisLine);
}

uc.setDoOutput(true);
DataOutputStream dos;
dos = new DataOutputStream(uc.getOutputStream());
// dos.writeByte("Here is some data");
try {
if (args.length != 1) {

System.out.println("Cach su dung: java TimDCIP <Hostname>");
}
InetAddress host = InetAddress.getByName(u.toString());
String hostName = host.getHostName();
System.out.println("Host name:" + hostName);
System.out.println("Dia chi IP:" + host.getHostAddress());
InetAddress me = InetAddress.getLocalHost();

byte[] address = me.getAddress();
for (int i = 0; i < address.length; i++) {
System.out.print(address[i] + " ");
}

} catch (Exception e) {
System.out.println("Khong tim thay dia chi");
return;

15


CHUẨN HÓA CHUỖI
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package InOutPut;

import java.io.FileReader;
import java.io.FileWriter;

import java.io.IOException;

/**
*
* @author Hong Bich
*/
public class ReadWrite {

public static void ChuanHoa(String s) {
String temp[] = s.split(" ");
for (int i = 0; i < s.length(); i++) {
s += String.valueOf(temp[i].charAt(0)).toUpperCase() + temp[i].substring(1);
if (i < temp.length - 1) {
s += " ";
}
}
System.out.println("chuẩn hóa:" + s);
16


}

public static void main(String[] args) throws IOException {
try {

String fileName = "D:\\VB.txt";

// Đọc tâp tin vào chuỗi sb
FileReader fr = new FileReader(fileName);
StringBuffer sb = new StringBuffer();

char ca[] = new char[5];

// Đọc mỗi lần tối đa 5 ký tự

while (fr.ready()) {
int len = fr.read(ca);

// len: số ký tự đọc được thật sự

sb.append(ca, 0, len);
}
fr.close();
//Xuất chuỗi sb
System.out.println("Du lieu doc duoc : " + sb);
// chuẩn hóa
String filename1 = "D:\\ChuanHoa.txt";
FileWriter fw = new FileWriter(fileName);
String s = ChuanHoa(sb);
fw.write(sb);
fw.close();
} catch (Exception e) {

Xét trên 1024 cổng nào đang hoạt động
17


import java.net.*;
import java.io.*;
class PortScanner
{

public static void main(String[] args)
{
String host="localhost";
if(args.length>0){
host=args[0];
}
for(int i=0;i<1024;i++){
try{
Socket s=new Socket(host,i);
System.out.println("Co mot server dang
hoat dong tren cong:"+i);
}
catch(UnknownHostException e){
System.err.println(e);
}
catch(IOException e){
System.err.println(e);
}
}
Ví dụ: Cài đặt một server daytime
import java.net.*;
import java.io.*;
import java.util.Date;
public class daytimeServer{
public final static int daytimePort =13;
public static void main(String[]args)
{
ServerSocket theServer;
Socket con;
18



PrintStream p;
try{
theServer = new ServerSocket(daytimePort);
try{
p= new PrintStream(con.getOutputStream());
p.println(new Date());
con.close();
}
catch(IOException e)
{
theServer.close();
System. err.println(e);
}
}
catch(IOException e)
{
System. err.println(e);
}
}
}

Ví dụ: Viết chương trình client liên kết với một server. Người sử dụng nhập vào một
dòng ký tự từ bàn phím và gửi dữ liệu cho server.
import java.net.*;
import java.io.*;
public class EchoClient1
{
public static void main(String[] args)

{
String hostname="localhost";
if(args.length>0)
{
hostname=args[0];
}
PrintWriter pw=null;
BufferedReader br=null;
19


try{
Socket s=new Socket(hostname,2007);
br=newBufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader user;
user=new BufferedReader(new InputStreamReader(System.in));
pw=new PrintWriter(s.getOutputStream());
System.out.println("Da ket noi duoc voi server...");
while(true)
{
String st=user.readLine();
if(st.equals("exit"))
{
break;
}
pw.println(st);
pw.flush();
System.out.println(br.readLine());
}
}

catch(IOException e)
{
System.err.println(e);
}
finally{
try{
if(br!=null)br.close();
if(pw!=null)pw.close();
}
catch(IOException e)
{
System.err.println(e);
}
}
}

20


Trong phần dưới đây chúng ta sẽ xem xét cách tiến hành cài đặt một chương trình client/server đa tuyến
đoạn.
Chương trình phía server
import java.io.*;
import java.net.*;
class EchoServe extends Thread
{
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public EchoServe (Socket s) throws IOException

{
socket = s;
System.out.println("Serving: "+socket);
in
=
new
InputStreamReader(socket.getInputStream()));

BufferedReader(new

// Cho phép auto-flush:
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
// Nếu bất kỳ lời gọi nào ở trên đưa ra ngoại lệ
// thì chương trình gọi có trách nhiệm đóng socket. Ngược lại
tuyến đoạn sẽ
// sẽ đóng socket
start();
}
public void run()
{
try{
while (true)
{
System.out.println("....Server is waiting...");
String str = in.readLine();
if (str.equals(“exit”) ) break;
System.out.println("Received: " + str);
System.out.println("From: "+ socket);
21



String upper=str.toUpperCase();
// gửi lại cho client
out.println(upper);
}
System.out.println("Disconnected with.."+socket);
}catch (IOException e) {}
finally{
try{
socket.close();
}
catch(IOException e) {}
}
}
}
public class TCPServer1
{
static int PORT=0; .
public static void main(String[] args) throws IOException
{
if (args.length == 1)
{
PORT=Integer.parseInt(args[0]); // Nhập số hiệu cổng từ đối dòng
lệnh
}
// Tạo một đối tượng Server Socket
ServerSocket s = new ServerSocket(PORT);
InetAddress addrs= InetAddress.getLocalHost();
System.out.println("TCP/Server running on : "+ addrs +" ,Port

"+s.getLocalPort());
try {
while(true) {
// Phong tỏa cho tới khi có một liên kết đến
Socket socket = s.accept();
try {
new EchoServe(socket);

22


// Tạo một tuyến đoạn quản lý riêng từng liên kết
} catch(IOException e) {
socket.close();
}
}
}
finally {
s.close();
}
}
}
Chương trình phía client
import java.net.*;
import java.io.*;
public class TCPClient1
{
public static void main(String[] args) throws IOException
{
if (args.length != 2) {

System.out.println("Sử dụng: java TCPClient hostid port#");
System.exit(0);
}
try{
InetAddress addr = InetAddress.getByName(args[0]);
Socket socket = new Socket(addr, Integer.parseInt(args[1]));
try {
System.out.println("socket = " + socket);
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
// Output is automatically flushed by PrintWriter:
PrintWriter out =new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),true);
// Đọc dòng ký tự từ bàn phím
DataInputStream
myinput
BufferedInputStream(System.in));

=

new

DataInputStream(new

23


try
{
for(;;){

System.out.println("Type anything followed by RETURN, or Exit
to terminate the program.");
String strin=myinput.readLine();
// Quit if the user typed ctrl+D
if (strin.equals("exit")) break;
else
out.println(strin);

// Send the message

String strout = in.readLine();

// Recive it back

if ( strin.length()==strout.length())
{ // Compare Both Strings
System.out.println("Received: "+strout);
} else
System.out.println("Echo bad -- string unequal"+ strout);
} // of for ;;
}catch (IOException e){
e.printStackTrace();
}
// User is exiting
}
finally
{
System.out.println("EOF...exit");
socket.close();
}

}
catch(UnknownHostException e)
{
System.err.println("Can't find host");
System.exit(1);
} catch (SocketException e)
{
System.err.println("Can't open socket");
24


e.printStackTrace();
System.exit(1);

Để dùng các stream, trước hết cần import package java.io.
import java.io.*;

Dưới đây sẽ trình bày các ví dụ về file stream và piped stream.
File stream:
String fileName="C:\\TestB.txt";
// Phát sinh và xuất mảng ngẫu nhiên
byte[]a=new byte[10];
System.out.print("Du lieu phat sinh: ");
for(int i=0;i{
a[i]=(byte)Math.round(Math.random()*20);
System.out.print(a[i]+" ");
}
System.out.println();
// Ghi mảng a vào tập tin

FileOutputStream fo=new FileOutputStream(fileName);
fo.write(a);
fo.close();
// Đọc tập tin vào mảng b
FileInputStream fi=new FileInputStream (fileName);
byte[]b= new byte[fi.available()];
fi.read(b);
fi.close();
// Xuất mảng b
System.out.print("Du lieu doc duoc : ");
for(int i=0;i{
System.out.print(b[i]+" ");
}
System.out.println();
25


×