The client part.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPsend {
/**
* direction: This is a client. The process has used UDP protocol. The code
* is a example to tell us how to build connection to server and send
* message.
*
* (1)We should create a DatagramSocket object and specify the value of
* itself port. which is also called build UDP connection.
* (2)We should make a packet which has some information about data, length,IP and server port
* (3)Sends your packet.
*
*/
public static void main(String[] args) throws IOException {
DatagramSocket s = new DatagramSocket(8888);
String str = "Welcome to Shandong Normal University";
byte[] buf = str.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length,
InetAddress.getByName("127.0.0.1"), 10000);
s.send(packet);
}
}
The server part.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPreceive {
/**
* directions:
* This is a server, you can receive message from a client.
*
* (1)Building UDP connection.
* (2)Prepares a packet for receive a message.
* (3)Receive.
* (4)We can use the packet we has received to get IP,Port and message.
*
*/
public static void main(String[] args) throws IOException {
DatagramSocket s = new DatagramSocket(10000);
byte[] buf = new byte[100];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
s.receive(packet);
byte[] data = packet.getData();
String str = new String(data, 0, packet.getLength());
String hostadd = packet.getAddress().getHostAddress();
int port = packet.getPort();
System.out.print("HostAddress:" + hostadd + ",Port:" + port + ",信息:"
+ str);
}
}