Java實驗六: Java流式程式設計與網路程式設計(頭歌)

Cloudservice發表於2024-05-27

一、位元組輸入/輸出流實現資料的儲存和讀取

package step1;
 
 
import java.io.*;
import java.util.*;
 
public class SortArray {
 
    public static void main(String[] args) {
        /********** Begin **********/
        // 建立儲存整型資料的陣列(陣列大小10)
        int[] data = new int[10];
 
        // 給陣列賦隨
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < data.length; i++) {
            data[i] = sc.nextInt();
        }
        // 將陣列元素按有小到大順序排列
        Arrays.sort(data);
 
        try {
            // 建立資料儲存檔案,如果檔案不存在,重新建立
            File file = new File("data.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            // 建立FileOutputStream和DataOutputStream 輸出流
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream);
 
            // 利用輸出流向檔案中寫入陣列資料
            for (int datum : data) {
                dataOutputStream.writeInt(datum);
            }
 
            // 關閉輸出流
            dataOutputStream.close();
 
            // 建立FileInputStream和DataInputStream 輸入流
            FileInputStream fileInputStream = new FileInputStream(file);
            DataInputStream dataInputStream = new DataInputStream(fileInputStream);
 
            // 利用輸入流從檔案讀取資料並輸出
            for (int i = 0; i < data.length; i++) {
                System.out.print(dataInputStream.readInt());
                if (i != data.length - 1) {
                    System.out.print("<");
                }
            }
            System.out.println();
            // 關閉輸入流
            dataInputStream.close();
 
        } catch (IOException e) {
            // 異常處理
            System.out.println("讀寫發生異常");
        }
        /********** End **********/
    }
}

二、字元輸入/輸出流實現傳送電報

package step2;
 
import java.io.*;
import java.util.Scanner;
 
public class Encrypt {
  public static void main(String[] args) throws IOException {
 
    // 建立要傳送的電報
    Scanner sc = new Scanner(System.in);
    String data = sc.next();
 
    // 將電報分割成字元陣列
    /********** Begin **********/
    char[] a = data.toCharArray();
    /********** End **********/
 
    // 開啟指定存放電報的檔案,如果檔案不存在,則建立
    File file = new File("data.txt");
    if (!file.exists()) {
      file.createNewFile();
    }
 
    // 迴圈遍歷字元陣列,將每個字元加密處理
    for (int i = 0; i < a.length; i++) {
      a[i] = (char)(a[i] ^ 'q');
    }
 
    // 利用字元輸出流FileWriter將加密後的字元陣列寫入檔案中
    /********** Begin **********/
    FileWriter fileWriter = new FileWriter(file);
    fileWriter.write(a, 0, a.length);
    fileWriter.flush();
    fileWriter.close();
    /********** End **********/
 
    // 利用字元輸入流FileReader讀取檔案,將密文輸出
    /********** Begin **********/
    FileReader fileReader = new FileReader(file);
    char[] buffer = new char[10];
    int x; //儲存讀取的資料量
    System.out.println("密文:");
    while ((x = fileReader.read(buffer)) != -1) {
      System.out.print(new String(buffer));
    }
    fileReader.close();
    /********** End **********/
 
    // 利用字元輸入流FileReader讀取檔案,將密文轉換為明文輸出
    /********** Begin **********/
    FileReader in = new FileReader(file);
    System.out.println("\n明文:");
    while ((x = in.read(buffer)) != -1) {
      for (int i = 0; i < x; i++) {
        buffer[i] = (char)(buffer[i] ^ 'q');
      }
      System.out.print(new String(buffer));
    }
    in.close();
    /********** End **********/
  }
}

三、簡單TCP通訊

客戶端程式

Client.java程式碼

package step3;
 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
 
public class Client {
 
    public static void main(String[] args) throws Exception {
        Server server = new Server();
        server.start();
        Scanner sc = new Scanner(System.in);
 
        //建立客戶端Socket(s),指定伺服器端IP地址和埠號
        /********** Begin **********/
        Socket s = new Socket("127.0.0.1", 8080);
 
        /**********  end  **********/
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        DataInputStream dis = new DataInputStream(s.getInputStream());
        System.out.println(dis.readUTF());
        String name = sc.next();
        dos.writeUTF(name);
        System.out.println(dis.readUTF());
        s.close();
    }
}

伺服器端程式

Server.java程式碼

package step3;
 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
 
public class Server extends Thread {
 
    @Override
    public void run() {
        try {
            //建立伺服器端ServerSocket(ss),指定埠號8000
            /********** Begin **********/
            ServerSocket ss = new ServerSocket(8080);
            /**********  end  **********/
            Socket s = ss.accept();
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            DataInputStream dis = new DataInputStream(s.getInputStream());
            dos.writeUTF("你已經連上伺服器了,告訴我你的姓名...");
            String name = dis.readUTF();
            dos.writeUTF("再見:" + name);
            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

四、TCP通訊實現奇偶數判斷

ClientPlus.java

package step4;
 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
 
public class ClientPlus {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ServerPlus server = new ServerPlus();
        server.start();
        try {
            //建立客戶端Socket(s),指定伺服器端IP地址和埠號
            /********** Begin **********/
            Socket s = new Socket("127.0.0.1", 8080);
            /**********  end  **********/
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            DataInputStream dis = new DataInputStream(s.getInputStream());
            //客戶端透過迴圈依次接收伺服器返回的結果,並輸入新的整數傳遞給伺服器
            /********** Begin **********/
            while (true) {
                System.out.println(dis.readUTF());
                String num = sc.next();
                dos.writeUTF(num);
            }
            /**********  end  **********/
        } catch (EOFException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ServerPlus.java

package step4;
 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
 
public class ServerPlus extends Thread {
    @Override
    public void run() {
        try {
            /********** Begin **********/
            //建立伺服器端ServerSocket(ss),指定埠號8000
            ServerSocket ss = new ServerSocket(8080);
            /**********  end  **********/
            Socket s = ss.accept();
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            DataInputStream dis = new DataInputStream(s.getInputStream());
            ReceiveThread thread = new ReceiveThread(s, dos, dis);
            thread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ReceiveThread.java

package step4;
 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
 
class ReceiveThread extends Thread {
    DataOutputStream dos;
    DataInputStream dis;
    Socket s;
    public ReceiveThread(Socket s, DataOutputStream dos, DataInputStream dis) {
        this.s = s;
        this.dos = dos;
        this.dis = dis;
    }
    @Override
    public void run() {
        try {
            dos.writeUTF("請輸入一個整數,我知道是奇數還是偶數");
            while(true) {
                String num = dis.readUTF();
                if("-1".equals(num)) {
                    s.close();
                    break;
                } 
                String result = (Integer.parseInt(num)%2==0)?"偶數":"奇數";
                dos.writeUTF(num + "是..." + result);
            }            
        } catch (SocketException e) {
            try {
                s.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } catch (IOException e) {
            System.out.println("資料讀取異常");
        } 
    }    
}

相關文章