本次實(shí)驗(yàn)主要涉及Java輸入輸出和網(wǎng)絡(luò)編程。在本實(shí)驗(yàn)中,我們熟悉了Java輸入輸出和網(wǎng)絡(luò)編程的基本原理和操作。
在Java中,輸入輸出和網(wǎng)絡(luò)通信都是通過IO操作來實(shí)現(xiàn)的。我們主要使用了BufferedReader、InputStreamReader、PrintWriter、Socket等類。下面是實(shí)現(xiàn)讀取文件并輸出的代碼:
try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); PrintWriter pw = new PrintWriter(new FileOutputStream("output.txt")); String line; while ((line = br.readLine()) != null) { pw.println(line); } br.close(); pw.close(); } catch (IOException e) { e.printStackTrace(); }
接下來我們實(shí)現(xiàn)了客戶端和服務(wù)器之間基本的通信??蛻舳送ㄟ^Socket對象連接服務(wù)器,并通過PrintWriter向服務(wù)器發(fā)送消息。服務(wù)器也使用Socket對象接收客戶端發(fā)來的消息,然后通過PrintWriter將消息輸出到客戶端。下面是簡單的代碼實(shí)現(xiàn):
// 服務(wù)器代碼 try { ServerSocket serverSocket = new ServerSocket(9999); Socket socket = serverSocket.accept(); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter pw = new PrintWriter(socket.getOutputStream()); String line; while ((line = br.readLine()) != null) { pw.println(line); pw.flush(); } br.close(); pw.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } // 客戶端代碼 try { Socket socket = new Socket("localhost", 9999); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream()); out.println("Hello world!"); out.flush(); String line = in.readLine(); System.out.println("服務(wù)器返回:" + line); in.close(); out.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); }
通過本次實(shí)驗(yàn),我們更加深入地理解了Java輸入輸出和網(wǎng)絡(luò)編程的基本原理和操作,并通過實(shí)際代碼實(shí)現(xiàn)對其的應(yīng)用。