当使用UDP协议,客户端接收服务器响应消息,没有完全显示出
public class UDPRunnable extends Thread{
DatagramPacket packet;;
//初始化DatagramPacket, DatagramSocket
public UDPRunnable(DatagramPacket packet){
this.packet=packet;
}
public void run() {
byte[] data=packet.getData();//!!!这里应该使用packet的getData方法来创建data字节,不然data字节中为空值
String info=new String(data,0,packet.getLength());//
System.out.println("我是服务器,客户端说:"+info);
/*
* 服务器向客户端发送响应信息
*/
//需要知道客户端的address,port,并且创建需要发送的消息
InetAddress address=packet.getAddress();
int port=packet.getPort();
byte[] data2="客户端登陆成功,欢迎使用服务器".getBytes();
//创建DatagramPacket
DatagramPacket packet2=new DatagramPacket(data2,data2.length,address,port);
try {
DatagramSocket socket=new DatagramSocket();
socket.send(packet2);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class UDPClient {
public static void main(String[] args) throws IOException {
/*
* 向服务器端发送消息
*/
//1.需要获取服务器端的地址,端口号
InetAddress address=InetAddress.getByName("localhost");
int port=6605;
byte[] message="用户名:admin 密码:123".getBytes();
//创建数据报
DatagramPacket packet=new DatagramPacket(message,message.length,address,port);
//创建DatagramSocket
DatagramSocket socket=new DatagramSocket();
socket.send(packet);
/*
* 接收服务器端发送的响应消息
*/
//创建DatagramPacket
byte[] data=new byte[10*1024];
DatagramPacket packet2=new DatagramPacket(data,data.length);
socket.receive(packet2);
String reply=new String(data,0,packet.getLength());
System.out.println("我是客户端,服务器说:"+reply);
}
}
客户端输出结果: 客户端启动成功,欢迎使