java socket例子

無名_四葉草發表於2020-04-05

轉自:http://liudaoru.iteye.com/blog/281287

今天看了一下socket,覺得這篇文字不錯。轉過來,以後學習一下。

服務端程式碼:

public class Server {
 
   public static void main(String args[]) throws IOException {
      //為了簡單起見,所有的異常資訊都往外拋
      int port = 8899;
      //定義一個ServerSocket監聽在埠8899上
      ServerSocket server = new ServerSocket(port);
      while (true) {
         //server嘗試接收其他Socket的連線請求,server的accept方法是阻塞式的
         Socket socket = server.accept();
         //每接收到一個Socket就建立一個新的執行緒來處理它
         new Thread(new Task(socket)).start();
      }
   }
   
   /**
    * 用來處理Socket請求的
    */
   static class Task implements Runnable {
 
      private Socket socket;
      
      public Task(Socket socket) {
         this.socket = socket;
      }
      
      public void run() {
         try {
            handleSocket();
         } catch (Exception e) {
            e.printStackTrace();
         }
      }
      
      /**
       * 跟客戶端Socket進行通訊
      * @throws Exception
       */
      private void handleSocket() throws Exception {
         BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
         StringBuilder sb = new StringBuilder();
         String temp;
         int index;
         while ((temp=br.readLine()) != null) {
            System.out.println(temp);
            if ((index = temp.indexOf("eof")) != -1) {//遇到eof時就結束接收
             sb.append(temp.substring(0, index));
                break;
            }
            sb.append(temp);
         }
         System.out.println("客戶端: " + sb);
         //讀完後寫一句
       Writer writer = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
         writer.write("你好,客戶端。");
         writer.write("eof\n");
         writer.flush();
         writer.close();
         br.close();
         socket.close();
      }
   }
}

客戶端程式碼:

public class Client {
 
   public static void main(String args[]) throws Exception {
      //為了簡單起見,所有的異常都直接往外拋
     String host = "127.0.0.1";  //要連線的服務端IP地址
     int port = 8899;   //要連線的服務端對應的監聽埠
     //與服務端建立連線
     Socket client = new Socket(host, port);
      //建立連線後就可以往服務端寫資料了
     Writer writer = new OutputStreamWriter(client.getOutputStream(), "GBK");
      writer.write("你好,服務端。");
      writer.write("eof\n");
      writer.flush();
      //寫完以後進行讀操作
     BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
      //設定超時間為10秒
     client.setSoTimeout(10*1000);
      StringBuffer sb = new StringBuffer();
      String temp;
      int index;
      try {
         while ((temp=br.readLine()) != null) {
            if ((index = temp.indexOf("eof")) != -1) {
                sb.append(temp.substring(0, index));
                break;
            }
            sb.append(temp);
         }
      } catch (SocketTimeoutException e) {
         System.out.println("資料讀取超時。");
      }
      System.out.println("服務端: " + sb);
      writer.close();
      br.close();
      client.close();
   }
}


相關文章