You must send a UDP packet and get a response in Java

I need to send a UDP packet and get a response from a UDP server. I, although UDP was similar to java.net.DatagramPacket in Java, but the documentation for DatagramPacket seems to be that you are sending a packet but not receiving anything, is this the right thing to use or should I use java. net.Socket

+5
source share
4 answers

Example of sending and receiving UDP datagram ( source ):

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

class UDPClient
{
   public static void main(String args[]) throws Exception
   {
      BufferedReader inFromUser =
         new BufferedReader(new InputStreamReader(System.in));
      DatagramSocket clientSocket = new DatagramSocket();
      InetAddress IPAddress = InetAddress.getByName("localhost");
      byte[] sendData = new byte[1024];
      byte[] receiveData = new byte[1024];
      String sentence = inFromUser.readLine();
      sendData = sentence.getBytes();
      DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
      clientSocket.send(sendPacket);
      DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
      clientSocket.receive(receivePacket);
      String modifiedSentence = new String(receivePacket.getData());
      System.out.println("FROM SERVER:" + modifiedSentence);
      clientSocket.close();
   }
}
+10
source

DatagramPacket DatagramSocket. , . , , , (, )

http://docs.oracle.com/javase/7/docs/api/java/net/DatagramSocket.html

Socket TCP-.

+2

UDP TCP-.

UDP , TCP java.net.Socket - -. UDP fire-and-forget, JMS.

: http://docs.oracle.com/javase/tutorial/networking/datagrams/index.html

+2

All Articles