客戶諮詢<基於UDP協議的Socket編程(數據報式套接字)>

一、DatagramPacket類的構造方法java

二、DatagramSocket類的構造方法數組

三、DatagramSocket類經常使用方法服務器

四、服務端app

 package com.ljb.app.datagram;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.net.SocketException;
/**
 * 客戶諮詢服務端
 * @author LJB
 * @version 2015年3月12日
 */
public class AskServer {
 /**
  * @param args
  */
 public static void main(String[] args) {
  try {
   // 建立接收方套接字(服務器),並綁定端口號
   DatagramSocket ds = new DatagramSocket(8800);
   // 肯定數據包接收的數據的數組的大小
   byte[] buf = new byte[1024];
   
   // 建立接收類型的數據包,數據將存儲在數組中
   DatagramPacket dp = new DatagramPacket(buf,buf.length);
   
   // 經過套接字接收數據
   ds.receive(dp);
   
   // 解析發送方發送的數據
   String mess = new String(buf , 0 , dp.getLength());
   System.out.println("客戶端說:" + mess);
   
   // 響應信息
   String reply = "您好,我在,請諮詢。";
   byte[] buf2 = reply.getBytes();
   
   // 響應地址
   SocketAddress sa = dp.getSocketAddress();
   
   // 數據包
   DatagramPacket dp2 = new DatagramPacket(buf2 , buf2.length , sa);
   
   // 發送
   ds.send(dp2);
   
   // 釋放資源
   ds.close();
  } catch (SocketException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  
  
 }
}

五、客戶端spa

package com.ljb.app.datagram;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
 * 客戶諮詢客戶端
 * @author LJB
 * @version 2015年3月12日
 */
public class AskClient {
 /**
  * @param args
  */
 public static void main(String[] args) {
  // 肯定發送給服務器的信息,服務器地址,端口
  String mess = "你好,我想諮詢一個問題?";
  byte[] buf = mess.getBytes();
  
  InetAddress ia = null;
  try {
   ia = InetAddress.getByName("localhost");
  } catch (UnknownHostException e) {
   e.printStackTrace();
  }
  
  int port = 8800;
  
  // 建立數據包,發送指定長度的信息到指定服務器的指定端口
  DatagramPacket dp = new DatagramPacket(buf , buf.length , ia , port);
  
  // 建立套接字對象
  DatagramSocket ds = null;
  try {
   ds = new DatagramSocket();
  } catch (SocketException e) {
   e.printStackTrace();
  }
  
  // 發送數據包
  try {
   ds.send(dp);
  } catch (IOException e) {
   e.printStackTrace();
  }
  
  // 建立接收數組
  byte[] buf2 = new byte[1024];
  
  // 建立接收數據包
  DatagramPacket dp2 = new DatagramPacket(buf2 , buf2.length);
  
  // 接收數據
  try {
   ds.receive(dp2);
  } catch (IOException e) {
   e.printStackTrace();
  }
  
  // 解析接收到的數據
  String reply = new String(buf2 , 0 , dp2.getLength());
  System.out.println("服務器端說:" + reply);
  
  // 釋放資源
  ds.close();
 }
}

運行結果:.net

服務端:code

            客戶端說:你好,我想諮詢一個問題?對象

客戶端:資源

            服務器端說:您好,我在,請諮詢。get

相關文章
相關標籤/搜索