package com.test;
/*
* 客户端类
*/
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
public class UDPclient {
public static void main(String[] args) throws IOException {
/*
* 向服务端发送信息
*/
//定义客户端地址、端口和数据
InetAddress address=InetAddress.getLocalHost();
int port=8800;
byte[] data="user:tom;key:123".getBytes();
//创建DatagramPacket对象,包含数据信息
DatagramPacket packet=new DatagramPacket(data, data.length, address, port);
//创建DatagramSocket对象
DatagramSocket socket=new DatagramSocket();
//发送数据
socket.send(packet);
/*
* 接收服务端信息
*/
//创建另一个DatagramSocket对象
DatagramSocket socket2=new DatagramSocket();
//创建数据报,用于接收信息
byte[] data2=new byte[1024];
DatagramPacket packet2=new DatagramPacket(data2, data2.length);
//接收信息
socket2.receive(packet2);
//输出信息
String reply=new String(data2);
System.out.println("我是客户端,服务器说:"+reply);
//关闭资源
socket.close();
socket2.close();
}
}