熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java Socket編程UDP

2022-06-13   來源: Java核心技術 

  看了下UDP編程的書寫了個簡單的例子代碼如下

  Java代碼

  import javaioIOException;

  import DatagramPacket;

  import DatagramSocket;

  import InetAddress;

  import SocketException;

  public class UDPReceive {

  public static void main(String[] args) {

  Integer port = ;

  byte[] buffer = new byte[];

  try {

  DatagramSocket datagramSocket = new DatagramSocket(port);

  DatagramPacket datagramPacket = new DatagramPacket(buffer

  bufferlength);

  try {

  for (;;) {

  Systemoutprintln(begin receive data);

  datagramSocketreceive(datagramPacket);

  Systemoutprintln(datagramPacketgetAddress()getAddress()toString()+=======+new String(datagramPacketgetData()));

  datagramPacketsetLength(datagramPacketgetData()toString()length());

  }

  } catch (IOException e) {

  eprintStackTrace();

  }

  } catch (SocketException e) {

  eprintStackTrace();

  }

  }

  }

  這個類用來接受消息

  Java代碼

  import javaioIOException;

  import DatagramPacket;

  import DatagramSocket;

  import InetAddress;

  import SocketException;

  import UnknownHostException;

  public class UDPSend {

  public static void main(String[] args) {

  try {

  for (;;) {

  DatagramSocket sendSocket = new DatagramSocket();

  DatagramPacket dataPack = new DatagramPacket(

  hello welcome to study javagetBytes()

  hello welcome to study javalength() InetAddress

  getByName() new Integer());

  try {

  sendSocketsend(dataPack);

  sendSocketclose();

  } catch (IOException e) {

  eprintStackTrace();

  }

  }

  } catch (SocketException e) {

  eprintStackTrace();

  } catch (UnknownHostException e) {

  eprintStackTrace();

  }

  }

  }

  這個類用來發送消息


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26024.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.