-
Notifications
You must be signed in to change notification settings - Fork 0
/
UDPClient.java
40 lines (32 loc) · 1.19 KB
/
UDPClient.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
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.georgiasouthern.csci5332;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
/**
*
* @author hzhang
*/
public class UDPClient {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
byte[] buf = "Hello, world!".getBytes();
InetAddress ip = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(buf, buf.length, ip, 5332);
socket.send(packet);
byte[] rbuf = new byte[256];
DatagramPacket rpacket = new DatagramPacket(rbuf, rbuf.length);
socket.receive(rpacket);
InetAddress rip = rpacket.getAddress();
int rport = rpacket.getPort();
System.out.println("ip addr: " + rip);
System.out.println("port: " + rport);
String msg = new String(rbuf, StandardCharsets.UTF_8);
System.out.println("msg: " + msg);
}
}