顯示具有 Java - 網路程式設計 課程 標籤的文章。 顯示所有文章
顯示具有 Java - 網路程式設計 課程 標籤的文章。 顯示所有文章

2009年6月24日

網路程式設計 - 期末考偷偷來 ( File I / O )

相關連結 http://caterpillar.onlyfun.net/Gossip/JavaGossip-V2/JavaGossip2.htm http://home.so-net.net.tw/idealist/Java/IO.html
package onlyfun.caterpillar;
 
import java.io.*;
import java.util.*;
 
public class FileDemo {
    public static void main(String[] args) {
        try { 
            String name = "FileDemo.java";//讀取的檔案或目錄
            File file = new File(name);
            if(file.isFile()) { // 是否為檔案
                System.out.println(name + " 檔案"); 
                System.out.println(
                      file.canRead() ? "可讀 " : "不可讀 "); 
                System.out.println(
                      file.canWrite() ? "可寫 " : "不可寫 "); 
                System.out.println(
                      file.length() + "位元組"); 
                /****************************************************/
                try {    
                    //讀取檔案
                    FileReader fis = new FileReader(name);
                    BufferedReader brdFile = new BufferedReader(fis);
                    //寫入檔案
                    FileWriter fOut = new FileWriter("c.txt");
                    BufferedWriter bwrFile = new BufferedWriter(fOut);
                    
                    //一行一行讀取並儲存 
                    int n = 0;
                    String strLine;
                    String str = "";
                    while ((strLine = brdFile.readLine()) != null) {
                        
                        str += (n++) + strLine + "\n";
                        
                    }
                    
                    //將字串一行一行寫入
                    String s = "";
                    for(int x = 0 ; x < str.length(); x++){
                        
                        if(str.charAt(x) != '\n'){
                            s += str.charAt(x);
                        }else{
                            bwrFile.write(s);//寫入一行
                            bwrFile.newLine();//換行
                            s = "";//字串重新儲存
                        }
                    }
                    
                    
                    System.out.println(str);
                    
                    //關閉檔案
                    brdFile.close();
                    bwrFile.close();
                    fOut.close();
                    fis.close();
                }catch (IOException e) {}
                /****************************************************/
            } 
            else { 
                // 列出所有的檔案及目錄
                File[] files = file.listFiles(); 
                ArrayList fileList = 
                                    new ArrayList(); 
                for(int i = 0; i < files.length; i++) { 
                    // 先列出目錄 
                    if(files[i].isDirectory()) { //是否為目錄
                        // 取得路徑名
                        System.out.println("[" + 
                                files[i].getPath() + "]"); 
                    }
                    else {
                        // 檔案先存入fileList,待會再列出
                        fileList.add(files[i]); 
                    }
                } 
 
                // 列出檔案 
                for(File f: fileList) {
                    System.out.println(f.toString());
                }
                System.out.println(); 
            } 
        } 
        catch(ArrayIndexOutOfBoundsException e) { 
            System.out.println(
                        "using: java FileDemo pathname"); 
        } 
    }
}

2009年6月23日

網路程式設計 - 期末考偷偷來 ( Network I / O )

相關連結 http://caterpillar.onlyfun.net/Gossip/JavaGossip-V2/JavaGossip2.htm http://home.so-net.net.tw/idealist/Java/IO.html
//Server.java

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Server extends JFrame {
    private JTextField enterField;
    private JTextArea displayArea;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private ServerSocket server;
    private Socket connection;
    private int counter = 1;

    // set up GUI
    // 設定 GUI
    public Server() {
        super( "Server" );

        Container container = getContentPane();

        // create enterField and register listener
        // 建立 enterField 設定 傾聽
        enterField = new JTextField();
        enterField.setEditable( false );
        enterField.addActionListener(
            new ActionListener() {
                // send message to client
                // 傳送 msg 到 client
                public void actionPerformed( ActionEvent event ) {
                    sendData( event.getActionCommand() );//傳送msg
                    enterField.setText( "" );
                }
            }    
        ); 

        container.add( enterField, BorderLayout.NORTH );

        // create displayArea
        // 建立 displayArea(顯示介面)
        displayArea = new JTextArea();
        container.add(new JScrollPane( displayArea ), 
                                    BorderLayout.CENTER );

        setSize( 300, 150 );
        setVisible( true );

    } // end Server constructor

    // set up and run server 
    // 設定 和 執行 server 
    public void runServer() {
        // set up server to receive connections; process connections
        // 接收連線 ; 處理連線
        try {
            // Step 1: Create a ServerSocket.
            // Step 1: 建立 ServerSocket.
            server = new ServerSocket(12345);

            while ( true ) {
                try {
                    // Step 2: Wait for a connection.
                    // Step 2: 等待連線
                    waitForConnection();
                    // Step 3: Get input & output streams.
                    // Step 3: 得到 I/O串流
                    getStreams();
                    // Step 4: Process connection.
                    // Step 4: 處理連線
                    processConnection();
                }
                // process EOFException when client closes connection
                // 當 closes 關閉連線 處理例外 
                catch ( EOFException eofException ) {
                    System.err.println( "Server 終止連線" );
                }
                finally {
                    // Step 5: Close connection.
                    // Step 5: 關閉連線
                    closeConnection();
                    ++counter;
                }
            } // end while
        } // end try

        // process problems with I/O
        // 處理 I/O 問題
        catch ( IOException ioException ) {
            ioException.printStackTrace();
        }

    } // end method runServer

    // Step 2: wait for connection to arrive, then display connection info
    // Step 2: 等待連線到達 並且 顯示連線訊息
    private void waitForConnection() throws IOException {
        displayMessage( "等待連線...\n" );
        // allow server to accept connection
        // 允許 server 接收連線                        
        connection = server.accept(); 
        displayMessage( "連線 " + counter + " 從 : " +
                 connection.getInetAddress().getHostName() );
    }

    // Step 3: get streams to send and receive data
    // Step 3: 接收 串流 和 接收 數據
    private void getStreams() throws IOException {
        // set up output stream for objects
        // 設定 objects 的 output(輸出) stream
        output = new ObjectOutputStream( connection.getOutputStream() );
        // flush output buffer to send header information
        // 輸出訊息
        output.flush(); 

        // set up input stream for objects
        // 設定 objects 的 input(輸入) stream
        input = new ObjectInputStream( connection.getInputStream() );

        displayMessage( "\n得到 I/O stream\n" );
    }

    // Step 4: process connection with client
    // Step 4: 處理連線
    private void processConnection() throws IOException {
        // send connection successful message to client
        // 傳送 連線成功訊息 給 client
        String message = "連線成功 !";
        sendData( message );

        // enable enterField so server user can send messages
        // 設定 enterField,讓 server 可以送 msg
        enterField.setEditable( true );

        // process messages sent from client
        // 處理從 client 傳送的訊息
        do { 
            // read message and display it
            // 讀取 msg 並且顯示
            try {
                message = ( String ) input.readObject();
                displayMessage( "\n" + message );
                
                sendData("訊息送達處理中...");//收到之後輸出..
                /*
                 
                 code...答案放置位址
                 
                 */
            }
            // catch problems reading from client
            catch ( ClassNotFoundException classNotFoundException ) {
                displayMessage( "\n未知 的類型" );
            }
        } while ( !message.equals( "CLIENT>>> TERMINATE" ) );
    } // end method processConnection

    // Step 5: close streams and socket
    // Step 5: 關閉連線
    private void closeConnection() {
        displayMessage( "\n終止連線\n" );
        // disable enterField
        // enterField 功能失效
        enterField.setEditable( false ); 

        try {
            output.close();
            input.close();
            connection.close();
        } catch( IOException ioException ) {
            ioException.printStackTrace();
        }
    }

    // send message to client
    // 傳送 msg 到 client
    private void sendData( String message ) {
        // send object to client
        // 傳送 物件 到 client
        try {
            output.writeObject( "SERVER>>> " + message );
            output.flush();
            displayMessage( "\nSERVER>>> " + message );
        }
        // process problems sending object
        // 處理錯誤
        catch ( IOException ioException ) {
            displayArea.append( "\n錯誤文字物件" );
        }
    }
    
    //印出 msg
    private void displayMessage( final String messageToDisplay ) {
        displayArea.append( messageToDisplay );
        displayArea.setCaretPosition(displayArea.getText().length() );
    }

    public static void main( String args[] ) {
        Server application = new Server();
        application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        application.runServer();
    }
}

2009年3月5日

Applet 基本結構

網路程式設計 2009/03/05 上課範例

2009年2月26日

網路程式設計 2009/02/26 作業-由n1加到n2

網路程式設計 2009/02/26 上課範例

無聊的第一堂課...