Untitled
5 years ago in Plain Text
class DgramUtils {
public DatagramPacket buildPkg(InetAddress addr, int port, String msg) throws IOException {
ByteArrayOutputStream bstream = new ByteArrayOutputStream();
DataOutputStream dstream = new DataOutputStream(bstream);
byte[] data;
dstream.writeUTF(msg);
data = bstream.toByteArray();
return new DatagramPacket(data, data.length, addr, port);
}
public String getCont(DatagramPacket pkg) throws IOException {
DataInputStream dstream = new DataInputStream(
new ByteArrayInputStream(pkg.getData(), 0, pkg.getLength())
);
return dstream.readUTF();
}
return dstream.readUTF();
}
}
public class server {
public static final int port = 3333;
private static void print(String msg) {
System.out.println(msg);
}
private static int cubo(int n) {
return (int)Math.pow(n, 3);
}
public static void main(String[] args) {
System.setProperty("java.net.preferIPv4Stack" , "true");
DgramUtils du = new DgramUtils();
byte[] buf = new byte[100];
DatagramSocket sock = null;
try {
sock = new DatagramSocket(port);
try {
sock = new DatagramSocket(port);
} catch (SocketException e) {
server.print("sock err: " + e.getMessage());
System.exit(1);
}
while (true) {
try {
DatagramPacket pkg = new DatagramPacket(buf, buf.length);
String cont;
int n;
server.print("rec");
sock.receive(pkg);
server.print("arec");
cont = du.getCont(pkg);
n = server.cubo(Integer.parseInt(cont));
buf = Integer.toString(n).getBytes();
pkg = new DatagramPacket(buf, buf.length, pkg.getAddress(), pkg.getPort());
server.print("rec " + n+" buf "+buf);
sock.send(pkg);
Arrays.fill(buf, (byte)0);
Arrays.fill(buf, (byte)0);
} catch (IOException e) {
e.printStackTrace();
continue;
} catch (Exception e) {
server.print("unk err: " + e.getMessage());
sock.close();
System.exit(1);
}
}
}
}