實驗四 面向SOCKET編程

實驗四 面向SOCKET編程

實驗目的:

1、理解SOCKET的基本原理;

2、學會面向SOCKET編程的代碼編寫及理解各語句內容;

3、掌握面向SOCKET編程的具體應用。

實驗要求:

1、建立兩個獨立的面向SOCKET編程的JAVA工程,用於服務器和客戶端系統;

2、建立SOCKETJAVA類,並能正確運行且能實現SOCKET通信;

3、對JAVA類的功能進行拓廣,使SOCKET用於某一具體的應用。

實驗內容:

1、建立服務器端工程和JAVA類,類程序的原代碼爲:

import java.io.*;

import java.net.*;

public class SocketServer {

  // 爲這個Socket選擇一個斷口8080:

  public static final int PORT = 8080;

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

    ServerSocket s = new ServerSocket(PORT);

    System.out.println("開始: " + s);

    try {

      // 生成一個Socket等待連接請求

      Socket socket = s.accept();

      try {

        System.out.println(

            "接受連接請求: " + socket);

        BufferedReader in =

            new BufferedReader(

            new InputStreamReader(

            socket.getInputStream()));

        // 定義一個PrintWriter對象寫輸出流

        PrintWriter out =

            new PrintWriter(

            new BufferedWriter(

            new OutputStreamWriter(

            socket.getOutputStream())), true);

        while (true) {

          String str = in.readLine();

          if (str.equals("END")) {

            break;

          }

          System.out.println("自客戶端: " + str);

          out.println(str);

        }

        // 關閉socket

      }

      finally {

        System.out.println("關閉...");

        socket.close();

      }

    }

    finally {

      s.close();

    }

  }

}

2、建立客戶端工程和JAVA類,類程序的原代碼爲:

import java.io.*;

import java.net.*;

import ch07.section03.*;

public class socketClient {

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

    // 指定使用本地IP

    InetAddress addr =

        InetAddress.getByName(null);

    System.out.println("addr = " + addr);

    Socket socket =

        new Socket(addr, SocketServer.PORT);

    // 將代碼放在Try語句中執行,以確保程序能關閉socket

    try {

      System.out.println("socket = " + socket);

      BufferedReader in =

          new BufferedReader(

          new InputStreamReader(

          socket.getInputStream()));

      // 定義一個PrintWriter對象寫輸出流

      PrintWriter out =

          new PrintWriter(

          new BufferedWriter(

          new OutputStreamWriter(

          socket.getOutputStream())), true);

      for (int i = 0; i < 10; i++) {

        out.println("測試 " + i);

        String str = in.readLine();

        System.out.println("自服務端: " + str);

      }

      out.println("END");

    }

    finally {

      System.out.println("關閉");

      socket.close();

    }

  }

}

3、調試使以上兩個工程能正常運行。

4、對服務器端和客戶端的程序代碼進行閱讀和理解,要求做到每條語句都能明白其具體含義,每個類都瞭解其功能。

5、對以上程序進行適當的修改,要求SOCKET通信功能保持實現。

(注:修改的方向有:圖形化界面、多SOCKET互訪、結合線程編程等。)

6、撰寫實驗報告

實驗報告包:實驗報告首頁、實驗步驟(每步的內容,有程序的要求有源碼和運行結果及結果描述)、實驗心得。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章