客户端:
服务器端:
package udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class SimpleClient {
private DatagramSocket socket; // udp套接字
DatagramPacket packet = null;// udp数据包
public static void main(String[] args) {
SimpleClient client = new SimpleClient();
try {
client.connect();
client.send();
client.disconnect();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void disconnect() {
socket.close();
}
private void send() throws IOException {
byte[] buf = new String("UDP TEST data from client").getBytes(); //创建发送数据缓冲区
// 数据包包括所有的信息,ip地址,端口号及要发送的数据
DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress
.getByName("localhost"), 8888);
// 发送请求
System.out.println("serverPort = " + 8888);
socket.send(packet);
System.out.println("packet.getData()=" + new String(packet.getData()));
}
private void connect() throws SocketException { //创建连接
socket = new DatagramSocket();
}
}
服务器端:
package udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class SimpleServer {
DatagramSocket socket; // udp套接字
DatagramPacket packet = null;// udp数据包
public static void main(String[] args) {
SimpleServer server = new SimpleServer();
try {
server.connect(8888); //连接
server.accept(); //接收请求
server.disconnect(); //关闭套接字
} catch (IOException e) {
e.printStackTrace();
}
}
private void disconnect() {
socket.close();
}
private void accept() throws IOException {
reveive();
}
private void reveive() throws IOException {
// 默认缓冲区大小,如果设置的缓冲区大小小于客户端发送的数据大小,怎么办??
byte[] buf = new byte[25];
packet = new DatagramPacket(buf, buf.length);
// 接收请求
socket.receive(packet);
System.out
.println("Received package = " + new String(packet.getData()));
}
private void connect(int port) throws SocketException { // 创建连接
socket = new DatagramSocket(port);
socket.setReceiveBufferSize(512);
}
}