亚洲欧洲国产欧美一区精品,激情五月亚洲色五月,最新精品国偷自产在线婷婷,欧美婷婷丁香五月天社区

      考試首頁 | 考試用書 | 培訓(xùn)課程 | 模擬考場 | 考試論壇  
      全國  |             |          |          |          |          |         
        當(dāng)前位置:計算機(jī)等級 > 二級考試 > Java語言程序設(shè)計 > 考試輔導(dǎo) > 文章內(nèi)容
        

      全國計算機(jī)等級考試Java語言程序設(shè)計輔導(dǎo)(93)

      中華IT學(xué)院   【 】  [ 2016年3月14日 ]

      如下的GreetingServer 程序是一個服務(wù)器端應(yīng)用程序,使用Socket來監(jiān)聽一個指定的端口。

      // 文件名 GreetingServer.java
      
      import java.net.*;
      import java.io.*;
      
      public class GreetingServer extends Thread
      {
         private ServerSocket serverSocket;
         
         public GreetingServer(int port) throws IOException
         {
            serverSocket = new ServerSocket(port);
            serverSocket.setSoTimeout(10000);
         }
      
         public void run()
         {
            while(true)
            {
               try
               {
                  System.out.println("Waiting for client on port " +
                  serverSocket.getLocalPort() + "...");
                  Socket server = serverSocket.accept();
                  System.out.println("Just connected to "
                        + server.getRemoteSocketAddress());
                  DataInputStream in =
                        new DataInputStream(server.getInputStream());
                  System.out.println(in.readUTF());
                  DataOutputStream out =
                       new DataOutputStream(server.getOutputStream());
                  out.writeUTF("Thank you for connecting to "
                    + server.getLocalSocketAddress() + "\nGoodbye!");
                  server.close();
               }catch(SocketTimeoutException s)
               {
                  System.out.println("Socket timed out!");
                  break;
               }catch(IOException e)
               {
                  e.printStackTrace();
                  break;
               }
            }
         }
         public static void main(String [] args)
         {
            int port = Integer.parseInt(args[0]);
            try
            {
               Thread t = new GreetingServer(port);
               t.start();
            }catch(IOException e)
            {
               e.printStackTrace();
            }
         }
      }

      編譯以上 java 代碼,并執(zhí)行以下命令來啟動服務(wù),使用端口號為 6066:

      $ java GreetingServer 6066
      Waiting for client on port 6066...
      像下面一樣開啟客戶端:
      $ java GreetingClient localhost 6066
      Connecting to localhost on port 6066
      Just connected to localhost/127.0.0.1:6066
      Server says Thank you for connecting to /127.0.0.1:6066
      Goodbye!
      分享到:
      本文糾錯】【告訴好友】【打印此文】【返回頂部
      將考試網(wǎng)添加到收藏夾 | 每次上網(wǎng)自動訪問考試網(wǎng) | 復(fù)制本頁地址,傳給QQ/MSN上的好友 | 申請鏈接 | 意見留言 TOP
      關(guān)于本站  網(wǎng)站聲明  廣告服務(wù)  聯(lián)系方式  站內(nèi)導(dǎo)航  考試論壇
      Copyright © 2007-2013 中華考試網(wǎng)(Examw.com) All Rights Reserved