经测试,错误在于你打包时数据的长度不够:服务器端修改语句即可:
//packet=new DatagramPacket(buf,data.length(),address,port);
packet=new DatagramPacket(buf,buf.length,address,port);
//packet=new DatagramPacket(buf,data.length(),address,port);
packet=new DatagramPacket(buf,buf.length,address,port);
太感谢你了!第二个问题解决了!!^_^
能再帮我解决第一个问题吗?我修改客户端程序如下能实现一句句输出所有语句,但没办法判断服务器已经读取完数据并关闭了Socket,从而客户端该正常退出程序了。你有什么好办法吗?
public class UDPClient{
public static void main(String[] args)throws IOException{
boolean isEnd=true;
DatagramSocket Socket=new DatagramSocket();
while(isEnd){
byte[] buf=new byte[1024];
InetAddress address=InetAddress.getByName("202.114.121.209");
DatagramPacket packet=new DatagramPacket(buf,buf.length,address,1111);
Socket.send(packet);
packet=new DatagramPacket(buf,buf.length);
Socket.receive(packet);
int packetLength=packet.getLength();
System.out.println(packetLength);
if(packetLength>0){ //用packetLength最为循环判断的参数好像没用?
String received=new String(packet.getData());
System.out.println(packet.getAddress());
System.out.println(received.substring(0,packetLength));
}
else{
isEnd=false;
System.out.println("GAME OVER!");
}
}
Socket.close();
System.exit(-1);
}
}
if(received.substring(0,packetLength).equals("No more quotes.Goodbye.")==true){
isEnd=false;
System.out.println("GAME OVER!");
break;
}
if(packetLength>0){ //用packetLength最为循环判断的参数好像没用?
此判断语句好像没用的原因:
1、此判断语句原本就没用
2、因为如果语句Socket.receive(packet);没有获得数据包的话,他会一直阻塞在这个语句上,他后面的语句都不会执行!!!