uni

University stuff
git clone git://git.margiolis.net/uni.git
Log | Files | Refs | README | LICENSE

UDPClient.java (1190B)


      1 import java.io.*;
      2 import java.net.*;
      3 
      4 public class UDPClient {
      5 	public static void main(String[] args) throws Exception {
      6 		DatagramSocket cltsock;
      7 		DatagramPacket sendpack, recvpack;
      8 		InetAddress addr;
      9 		BufferedReader input;
     10 		String msg, srvresp;
     11 		String hostname = "127.0.0.1";
     12 		byte[] senddata = new byte[1024];
     13 		byte[] recvdata = new byte[1024];
     14 		int port = 8888;
     15 
     16 		if (args.length == 2) {
     17 			hostname = args[0];
     18 			port = Integer.parseInt(args[1]);
     19 		} else
     20 			System.out.println("usage: java UDPClient [hostname] [port]");
     21 		System.out.print("> ");
     22 		input = new BufferedReader(new InputStreamReader(System.in));
     23 		cltsock = new DatagramSocket();
     24 		cltsock.setSoTimeout(1000);
     25 		addr = InetAddress.getByName(hostname);
     26 		msg = input.readLine();
     27 		senddata = msg.getBytes();
     28 		sendpack = new DatagramPacket(senddata, senddata.length, addr, port);
     29 		cltsock.send(sendpack);
     30 		recvpack = new DatagramPacket(recvdata, recvdata.length);
     31 
     32 		try {
     33 			cltsock.receive(recvpack);
     34 			srvresp = new String(recvpack.getData());
     35 			System.out.println("server response: " + srvresp);
     36 		} catch (SocketTimeoutException e) {
     37 			System.err.println("timeout" + e);
     38 		}
     39 		cltsock.close();
     40 	}
     41 }