如何使用相同的DatagramPacket在UDP中发送和接收数据

时间:2017-05-22 09:31:37

标签: java udp

这里我创建了两个独立的数据包来发送和接收。取而代之的是,如何通过使用带有新数据缓冲区的setData方法覆盖数据来使用相同的数据包来回复:packet.setData(newbuffer);

  

客户端

package labsheet2;

import java.net.*;
import java.io.*;

public class Clientnew {
  public final static int UDP_PORT = 50001;
  public static void main(String[] args) throws Exception {
  System.out.println("Server Time >>>>");

  //create a DatagramSocket object
  DatagramSocket clientSocket = new DatagramSocket();
  InetAddress ip = InetAddress.getByName("localhost");

  //create buffers to store datagram data in DatagramPacket Objecct
  byte[] buffReceiveData = new byte[100]; //for incoming data
  byte[] buffSendData = new byte[100]; //for outgoing data

  //create the outgoing Datagram with ip and port
  DatagramPacket packetOut = new DatagramPacket(buffSendData, 
  buffSendData.length, ip, UDP_PORT);

  //create the incoming DatagramPacket object to wrap receiving data
  DatagramPacket packetIn = new DatagramPacket(buffReceiveData, 
  buffReceiveData.length);
  clientSocket.send(packetOut); //send data
  clientSocket.receive(packetIn); //receive data from the server
  String time = new String(packetIn.getData());
  System.out.println(time);
  clientSocket.close(); //close the client socket
}

}

  

服务器

package labsheet2;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;

public class Servernew {
public final static int UDP_PORT = 50001;
public static void main(String[] args) throws Exception {

//create a DatagramSocket and bind it to the PORT
DatagramSocket serverSocket = new DatagramSocket(UDP_PORT);
while (true) {
System.out.println("Server is up....");

//create buffers to store datagram data in DatagramPacket Objecct
byte[] buffReceiveData = new byte[100]; //for incoming data
byte[] buffSendData = new byte[100]; //for outgoing data

//Datagram object to wrap incoming data
DatagramPacket packetIn = new DatagramPacket(buffReceiveData, 
buffReceiveData.length);

//Receive the incoming data packet to DatagramPacket Object
serverSocket.receive(packetIn);

//Get the source ip from the incoming packet
InetAddress ip = packetIn.getAddress();

//Get the source port from the incoming packet
int port = packetIn.getPort();
buffSendData = new Date().toString().getBytes();//get Date in bytes

//packetIn.setData(buffReceiveData, buffReceiveData.length, ip, port); 

//create the outgoing Datagram with source ip and port
DatagramPacket packetOut = new DatagramPacket(buffSendData, 
buffSendData.length, ip, port);
serverSocket.send(packetOut);
packetIn = null; //reset incoming DatagramPacket Object
System.out.println("Done !! ");
}
}
}

1 个答案:

答案 0 :(得分:1)

  

如何使用相同的数据包通过覆盖数据,使用setData方法和新的数据缓冲区来回复:packet.setData(newbuffer);

通过覆盖数据,使用setData()方法和新数据缓冲区:packet.setData(newbuffer);