Java編程那些事兒106——網路編程技術5

來源:互聯網
上載者:User

該樣本的功能是實現將用戶端程式的系統時間發送給伺服器端,伺服器端接收到時間以後,向用戶端反饋字串“OK”。實現該功能的用戶端代碼如下所示:

package udp;
import java.net.*;
import java.util.*;
/**
* 簡單的UDP用戶端,實現向伺服器端發生系統時間功能
*/
public class SimpleUDPClient {
 public static void main(String[] args) {
  DatagramSocket ds = null;  //連線物件
  DatagramPacket sendDp; //發送資料包對象
  DatagramPacket receiveDp; //接收資料包對象
  String serverHost = "127.0.0.1"; //伺服器IP
  int serverPort = 10010;  //伺服器連接埠號碼
  try{
   //建立串連
   ds = new DatagramSocket();
   //初始化發送資料
   Date d = new Date(); //目前時間
   String content = d.toString(); //轉換為字串
   byte[] data = content.getBytes();
   //初始化發送包對象
   InetAddress address = InetAddress.getByName(serverHost);
   sendDp = new DatagramPacket(data,data.length,address,serverPort);
   //發送
   ds.send(sendDp);

   //初始化接收資料
   byte[] b = new byte[1024];
   receiveDp = new DatagramPacket(b,b.length);
   //接收
   ds.receive(receiveDp);
   //讀取反饋內容,並輸出
   byte[] response = receiveDp.getData();
   int len = receiveDp.getLength();
   String s = new String(response,0,len);
   System.out.println("伺服器端反饋為:" + s);
  }catch(Exception e){
    e.printStackTrace();
  }finally{
    try{
      //關閉串連
      ds.close();
    }catch(Exception e){}
  }
 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.