package cn.edu.sjtu.cit.apm.probe;

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

public class UDPClient {

    private DatagramSocket socket;
    private InetAddress ip;
    private Integer port;

    public UDPClient(String host, Integer port) throws SocketException, UnknownHostException {
        socket = new DatagramSocket();
        ip = InetAddress.getByName(host);
        this.port = port;
    }

    public String send(String data) throws IOException {
        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];
        System.out.println("want to send: " + data);
        sendData = data.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, port);
        socket.send(sendPacket);
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        socket.receive(receivePacket);
        return new String(receivePacket.getData());
    }

    public boolean registerInstance(String instanceName) throws IOException {
        String req = "APM_REGISTER:" + instanceName + ":" + Util.getPID();
        String res = send(req);
        // FIXME: the receive string has a long empty part ....
        if (res.startsWith("registered")) {
            System.out.println("registered");
            return true;
        } else {
            System.err.println("fail to register, collector return: " + res);
            return false;
        }
    }
}
@@ -407,31 +407,42 @@
 lic 
+UDPClient(
 String 
-send(
+host, 
 String 
-data
+port
 ) th
@@ -450,63 +450,155 @@
 ows 
-IOException %7B%0A        byte%5B%5D sendData = new byte%5B1024%5D;
+SocketException, UnknownHostException %7B%0A        this(host, Integer.parseInt(port));%0A    %7D%0A%0A    public String send(String data) throws IOException %7B
 %0A   
@@ -639,16 +639,18 @@
 %5B1024%5D;%0A
+//
         
@@ -701,16 +701,23 @@
 %0A       
+ byte%5B%5D
  sendDat
@@ -1346,16 +1346,18 @@
 ed%22)) %7B%0A
+//
         
@@ -1436,16 +1436,92 @@
  else %7B%0A
+            // TODO: store the error message and return in another method%0A//
         

Support string for port