-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUDPReceiver.java
41 lines (33 loc) · 1.16 KB
/
UDPReceiver.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
import java.net.*;
public class UDPReceiver {
private final static int PACKETSIZE = 100 ;
public static void main( String args[] )
{
// Check the arguments
if( args.length != 1 )
{
System.out.println( "usage: UDPReceiver port" ) ;
return ;
}
try
{
// Convert the argument to ensure that is it valid
int port = Integer.parseInt( args[0] ) ;
// Construct the socket
DatagramSocket socket = new DatagramSocket( port ) ;
for( ;; )
{
System.out.println( "Receiving on port " + port ) ;
DatagramPacket packet = new DatagramPacket( new byte[PACKETSIZE], PACKETSIZE ) ;
socket.receive( packet ) ;
System.out.println( packet.getAddress() + " " + packet.getPort() + ": " + new String(packet.getData()).trim() ) ;
DatagramPacket sendPacket = new DatagramPacket(packet.getData(), packet.getLength(), packet.getAddress(), packet.getPort());
socket.send(sendPacket);
}
}
catch( Exception e )
{
System.out.println( e ) ;
}
}
}