-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClienteUDP.java
47 lines (41 loc) · 1.72 KB
/
ClienteUDP.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package codigo;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import javax.swing.JOptionPane;
public class ClienteUDP {
private static int SERVER_PORT =9091;
/**
* Runs the client as an application. First it displays a dialog
* box asking for the IP address or hotsname of a ahost running
* the data server, then connects to it and displays the data that
* the server sends
*/
public static void main(String[] args) throws IOException {
String serverAddress = JOptionPane.showInputDialog("Enter Ip Addres of a machine that is running the data"
+ " service on port "+SERVER_PORT+";");
//Send packet (Request)
DatagramSocket clientSocket = new DatagramSocket();
byte bufferSend[] = serverAddress.getBytes(); //transforma Ip a bytes (String-bytes)
DatagramPacket sendPacket = new DatagramPacket(bufferSend, bufferSend.length,InetAddress.getByName(serverAddress),SERVER_PORT);
clientSocket.send(sendPacket);
//InetAddress solo transforma la IP a InetAddress
//Receive packet
byte bufferReceive[] = new byte[128];
DatagramPacket receivePacket = new DatagramPacket(bufferReceive, bufferReceive.length);
clientSocket.receive(receivePacket); //este packet esta en bytes
//Transform bytes to String
InputStream myInputStream = new ByteArrayInputStream(receivePacket.getData());
BufferedReader input = new BufferedReader(new InputStreamReader(myInputStream));
String answer = input.readLine();
//Display mensaje
JOptionPane.showMessageDialog(null,answer);
clientSocket.close();
System.exit(0);
}
}